[英]changing from tuple to list and vice versa
how could i change [('a', 1), ('c', 3), ('b', 2)]
to ['a',1,'c',3,'b',2]
and vice versa? 我怎么能把
[('a', 1), ('c', 3), ('b', 2)]
改为['a',1,'c',3,'b',2]
和反之亦然? Thanks 谢谢
Going in the first direction from [('a', 1), ('c', 3), ('b', 2)]
to ['a',1,'c',3,'b',2]
is flattening a list . 从
[('a', 1), ('c', 3), ('b', 2)]
到['a',1,'c',3,'b',2]
被压扁的列表 。 Taking the accepted answer from there and modifying for this example: 从那里接受接受的答案并修改此示例:
>>> L = [('a', 1), ('c', 3), ('b', 2)]
>>> list(itertools.chain(*L))
['a', 1, 'c', 3, 'b', 2]
This uses itertools.chain
which is a nice tool from itertools
that flattens sequences quite nicely. 这使用了
itertools.chain
,这是一个来自itertools
的很好的工具,可以很好地展平序列。
Going the opposite way is zipping: 相反的方式是拉链:
>>> L = ['a', 1, 'c', 3, 'b', 2]
>>> zip(L[0::2], L[1::2])
[('a', 1), ('c', 3), ('b', 2)]
zip
takes two lists and combines list 1's first element with list 2's first element in a tuple, and so on down the lengths of the list. zip
采用两个列表,并将列表1的第一个元素与列表2中元组的第一个元素组合在一起,依此类推列表的长度。 So in this one, we basically take the even-indexed elements as our first list ( L[0::2]
), and then the odd-indexed elements as our second ( L[1::2]
) 所以在这一个中,我们基本上将偶数索引元素作为我们的第一个列表(
L[0::2]
),然后将奇数索引元素作为我们的第二个( L[1::2]
)
Here it's my take on it (assuming a contains first list and b second): 这是我的看法(假设包含第一个列表,第二个列表):
b = []
for i in a:
b.extend(i)
And reverse: 反过来:
c = []
for i in range(0, len(b) - 1, 2):
c.append((b[i], b[i+1]))
L = [('a', 1), ('c', 3), ('b', 2)]
flat = [x for p in L for x in p]
assert flat == ['a', 1, 'c', 3, 'b', 2]
it = iter(flat)
L2 = zip(it, it)
assert L2 == L
print "Success"
There are already plenty of correct answers here, so this is just a reminder not to use sum() to flatten lists as although it looks like a neat solution unfortunately the performance is quadratic 这里已经有很多正确的答案了,所以这只是提醒我们不要使用sum()来压缩列表,尽管它看起来像一个简洁的解决方案但不幸的是性能是二次的
In [1]: L=[('a',x) for x in range(10)]
In [2]: timeit sum(L,())
100000 loops, best of 3: 2.78 us per loop
In [3]: L=[('a',x) for x in range(100)]
In [4]: timeit sum(L,())
10000 loops, best of 3: 108 us per loop
In [5]: L=[('a',x) for x in range(1000)]
In [6]: timeit sum(L,())
100 loops, best of 3: 8.02 ms per loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.