How To Merge an Arbitrary Number of Tuples in Python?
我有一个元组列表:
1 | l=[(1,2,3),(4,5,6)] |
列表可以是任意长度,元组也可以。我想把它转换成元素的列表或元组,按它们出现的顺序排列:
1 | f=[1,2,3,4,5,6] # or (1,2,3,4,5,6) |
号
如果我知道在开发时我会得到多少个元组,我可以添加它们:
1 | m = l[0] + l[1] # (1,2,3,4,5,6) |
但因为我不知道直到运行时我会有多少个元组,所以我不能这样做。我觉得有一种方法可以使用
将它们链接起来(只创建一个生成器而不是保留额外的内存):
1 2 3 4 | >>> from itertools import chain >>> l = [(1,2,3),(4,5,6)] >>> list(chain.from_iterable(l)) [1, 2, 3, 4, 5, 6] |
1 2 | l = [(1, 2), (3, 4), (5, 6)] print sum(l, ()) # (1, 2, 3, 4, 5, 6) |
对以下所有内容使用pythonic生成器样式:
1 2 3 4 5 6 7 8 | b=[(1,2,3),(4,5,6)] list = [ x for x in i for i in b ] #produces a list gen = ( x for x in i for i in b ) #produces a generator tup = tuple( x for x in i for i in b ) #produces a tuple print list >> [1, 2, 3, 4, 5, 6] |
。
1 | tuple(i for x in l for i in x) # (1, 2, 3, 4, 5, 6) |
。
1 | reduce(tuple.__add__, [(1,2,3),(4,5,6)]) |
号
1 2 3 4 | >>> from itertools import chain >>> l = [(1,2,3),(4,5,6)] >>> list(chain(*l)) [1, 2, 3, 4, 5, 6] |
您可以使用这样的
1 2 3 4 | l = [(1,2,3), (4,5,6)] m = [] for t in l: m.extend(t) |
。
或使用Reduce的较短版本:
1 2 | l = [(1,2,3), (4,5,6)] m = reduce(lambda x,y: x+list(y), l, []) |