Python元组解压缩

拉斐

如果我有

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

并希望

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

我将如何以Python的方式做到这一点?我花了一点时间才意识到以下原因为何不起作用

nums, words = [(el[0], el[1]) for el in nums_and_words]

我很好奇是否有人可以提供类似的方式来达到我想要的结果。

tobias_k

使用zip,然后解压缩:

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

实际上,这两次“解压缩”:首先,当您将列表传递给zipwith时*,然后将结果分配给两个变量。

您可以zip(*list_of_lists)将参数视为“转置”:

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

注意这会给你元组。如果您确实需要列表,则必须得到map以下结果:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章