[英](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
.如果你想保留顺序,你需要从set
切换到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.此外,集合是无序的,因此您无法保留顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.