Python元组解压缩 [英] Python Tuple Unpacking
问题描述
如果我有
nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')]
并且想要
nums = [1, 2, 3]
words= ['one', 'two', 'three']
我将如何以Pythonic的方式做到这一点?我花了一点时间才知道为什么下面的方法不起作用
How would I do that in a Pythonic way? It took me a minute to realize why the following doesn't work
nums, words = [(el[0], el[1]) for el in nums_and_words]
我很好奇有人是否可以提供类似的方式来达到我想要的结果.
I'm curious if someone can provide a similar manner of achieving the result I'm looking for.
推荐答案
使用 zip
,然后解压:
Use zip
, then unpack:
nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')]
nums, words = zip(*nums_and_words)
实际上,这两次解包":首先,当使用*
将列表列表传递给zip
时,然后将结果分配给两个变量.
Actually, this "unpacks" twice: First, when you pass the list of lists to zip
with *
, then when you distribute the result to the two variables.
您可以将zip(*list_of_lists)
视为转置"参数:
You can think of zip(*list_of_lists)
as 'transposing' the argument:
zip(*[(1, 'one'), (2, 'two'), (3, 'three')])
== zip( (1, 'one'), (2, 'two'), (3, 'three') )
== [(1, 2, 3), ('one', 'two', 'three')]
请注意,这将给您元组;如果您确实需要列表,则必须map
结果:
Note that this will give you tuples; if you really need lists, you'd have to map
the result:
nums, words = map(list, zip(*nums_and_words))
这篇关于Python元组解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!