Python 元组解包

标签 python list-comprehension iterable-unpacking

如果我有

 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/

相关文章:

Python动态函数生成

python - 测试值是否存在于多个列表中

python - 词典理解和创建过程中的键检查

python - 使用python psycopg2保存二进制数据时如何修复 "can' t adapt error

python - 元组解包类似于 Python,但在 Common Lisp 中

python - 根据其他列表对字典中的列表进行排序,而无需再次分配它们

python - Numpy arange float 不一致

PYTHON 2.6 XML.ETREE 输出属性的单引号而不是双引号

python - 如果集合是无序的,为什么集合会以相同的顺序显示?

python - 如何简化这些字典理解?