如何连接元组并将其放入单个项目列表中?

如何在 Python 中将列表中的不同元组连接到列表中的单个元组?

当前形式:

[('1st',), ('2nd',), ('3rd',), ('4th',)]

所需形式:

[('1st', '2nd', '3rd', '4th')]


烙印99
浏览 210回答 5
5回答

一只甜甜圈

您要做的是“展平”元组列表。最简单和最 pythonic 的方法是简单地使用(嵌套)理解:tups = [('1st',), ('2nd',), ('3rd',), ('4th',)]tuple(item for tup in tups for item in tup)结果:('1st', '2nd', '3rd', '4th')如果确实需要,可以将生成的元组包装在列表中。

牧羊人nacy

似乎这样可以做到:import itertoolstuples = [('1st',), ('2nd',), ('3rd',), ('4th',)][tuple(itertools.chain.from_iterable(tuples))]

拉莫斯之舞

>>> l = [('1st',), ('2nd',), ('3rd',), ('4th',)]>>> list(zip(*l))[('1st', '2nd', '3rd', '4th')]

DIEA

简单的解决方案:tups = [('1st',), ('2nd',), ('3rd',), ('4th',)]result = ()for t in tups:    result += t# [('1st', '2nd', '3rd', '4th')]print([result])

Smart猫小萌

这是另一个 - 只是为了好玩:[tuple([' '.join(tup) for tup in tups])]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python