简体   繁体   English

Python元组解包

[英]Python Tuple Unpacking

If I have 如果我有

 nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')]

and would like 并希望

nums = [1, 2, 3]
words= ['one', 'two', 'three']

How would I do that in a Pythonic way? 我怎么用Pythonic方式做到这一点? 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. 我很好奇是否有人可以提供类似的方式来实现我正在寻找的结果。

Use zip , then unpack: 使用zip ,然后解压缩:

nums_and_words = [(1, 'one'), (2, 'two'), (3, 'three')]
nums, words = zip(*nums_and_words)

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* ,然后将结果分发给两个变量。

You can think of zip(*list_of_lists) as 'transposing' the argument: 您可以将zip(*list_of_lists)视为“转置”参数:

   zip(*[(1, 'one'), (2, 'two'), (3, 'three')])
== zip(  (1, 'one'), (2, 'two'), (3, 'three') )
== [(1, 2, 3), ('one', 'two', 'three')]

Note that this will give you tuples; 请注意,这将为您提供元组; if you really need lists, you'd have to map the result: 如果你真的需要列表,你必须map结果:

nums, words = map(list, zip(*nums_and_words))

Using List comprehension .. 使用列表理解..

nums = [nums_and_words[x][0] for x in xrange(len(nums_and_words)) ]
words = [nums_and_words[x][1] for x in xrange(len(nums_and_words)) ]
Testing if this works 测试是否有效
 print nums ,'&', words 

Just unzip and create lists: 只需解压缩并创建列表:

nums = list(zip(*nums_and_words)[0])
word = list(zip(*nums_and_words)[1])

See the zip documentation. 请参阅zip文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM