如果我有
nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')]
想要
nums = [1, 2, 3]
words= ['one', 'two', 'three']
我如何以 Pythonic 的方式做到这一点?我花了一分钟才意识到为什么以下内容不起作用
nums, words = [(el[0], el[1]) for el in nums_and_words]
我很好奇是否有人可以提供类似的方式来实现我正在寻找的结果。
最佳答案
使用zip
,然后解压:
nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')]
nums, words = zip(*nums_and_words)
实际上,这“解包”了两次:首先,当您使用 *
将列表的列表传递给 zip
时,然后当您将结果分发给两个变量时。
您可以将 zip(*list_of_lists)
视为“转置”参数:
zip(*[(1, 'one'), (2, 'two'), (3, 'three')])
== zip( (1, 'one'), (2, 'two'), (3, 'three') )
== [(1, 2, 3), ('one', 'two', 'three')]
请注意,这将为您提供元组;如果您确实需要列表,则必须映射
结果:
nums, words = map(list, zip(*nums_and_words))
关于Python 元组解包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29019817/