在Python中,如何将列表中的不同元组连接到列表中的单个元组?
当前形式:
[('1st',), ('2nd',), ('3rd',), ('4th',)]
所需形式:
[('1st', '2nd', '3rd', '4th')]
您要做的是"压平";元组列表。最简单、最Python的方法是简单地使用(嵌套(理解:
tups = [('1st',), ('2nd',), ('3rd',), ('4th',)]
tuple(item for tup in tups for item in tup)
结果:
('1st', '2nd', '3rd', '4th')
如果确实需要,可以将生成的元组封装在列表中。
编辑:
我也喜欢Alan Cristian的答案,它基本上是将列向量转换为行向量:
list(zip(*tups))
似乎这样就可以了:
import itertools
tuples = [('1st',), ('2nd',), ('3rd',), ('4th',)]
[tuple(itertools.chain.from_iterable(tuples))]
>>> l = [('1st',), ('2nd',), ('3rd',), ('4th',)]
>>> list(zip(*l))
[('1st', '2nd', '3rd', '4th')]
另请参阅:使用Python zip((函数进行并行迭代
简单的解决方案:
tups = [('1st',), ('2nd',), ('3rd',), ('4th',)]
result = ()
for t in tups:
result += t
# [('1st', '2nd', '3rd', '4th')]
print([result])
这里还有一个-只是为了好玩:
[tuple([' '.join(tup) for tup in tups])]