简体   繁体   中英

(Python) converting a list of integers into tuples/sets changes positions of integers

I want to convert

E =[1,6,1,7,2,3,2,6,3,2,3,8,4,5,4,7,5,4,5,9,6,1,6,7,6,2,7,1,7,6,7,4,8,9,8,3,9,8,9,5,]

into

E = [{1,6},{1,7},{2,3},{2,6},{3,2},{3,8},{4,5},{4,7},{5,4},{5,9},{6,1},{6,7},{6,2},{7,1},{7,6},{7,4},{8,9},{8,3},{9,8},{9,5}

but I get

E=[[{1, 6}], [{1, 7}], [{2, 3}], [{2, 6}], [{2, 3}], [{8, 3}], [{4, 5}], [{4, 7}], [{4, 5}], [{9, 5}], [{1, 6}], [{6, 7}], [{2, 6}], [{1, 7}], [{6, 7}], [{4, 7}], [{8, 9}], [{8, 3}], [{8, 9}], [{9, 5}]]

instead, and also the order in the sets {.} all get mixed up (order not preserved).

Why is this the case and how can I solve this?

My code is:

def convert_to_set(x):
    sets = []
    l = len(x)
    for i in range(0,l,2):
        set1 = []      
        set1.append({x[i],x[i+1]})
        sets.append(set1)
    return sets

If you want to preserve order you'll need to switch from set to tuple . It's easily done this way:

list(zip(E[::2], E[1::2]))

That gives you:

[(1, 6),
 (1, 7),
 (2, 3),
 (2, 6),
 (3, 2),
...

One option is the following:

sets = [{E[i],E[i+1]} for i in range(0,len(E)-1,2)]

Moreover, sets are unordered so you cannot preserve the order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM