如何在 Python 中将列表中的不同元组连接到列表中的单个元组?当前形式:[('1st',), ('2nd',), ('3rd',), ('4th',)]所需形式:[('1st', '2nd', '3rd', '4th')]
5 回答

一只甜甜圈
TA贡献1836条经验 获得超5个赞
您要做的是“展平”元组列表。最简单和最 pythonic 的方法是简单地使用(嵌套)理解:
tups = [('1st',), ('2nd',), ('3rd',), ('4th',)]
tuple(item for tup in tups for item in tup)
结果:
('1st', '2nd', '3rd', '4th')
如果确实需要,可以将生成的元组包装在列表中。

牧羊人nacy
TA贡献1862条经验 获得超7个赞
似乎这样可以做到:
import itertools
tuples = [('1st',), ('2nd',), ('3rd',), ('4th',)]
[tuple(itertools.chain.from_iterable(tuples))]

拉莫斯之舞
TA贡献1820条经验 获得超10个赞
>>> l = [('1st',), ('2nd',), ('3rd',), ('4th',)]
>>> list(zip(*l))
[('1st', '2nd', '3rd', '4th')]

DIEA
TA贡献1820条经验 获得超2个赞
简单的解决方案:
tups = [('1st',), ('2nd',), ('3rd',), ('4th',)]
result = ()
for t in tups:
result += t
# [('1st', '2nd', '3rd', '4th')]
print([result])
添加回答
举报
0/150
提交
取消