具有元组分配的列表理解 [英] List comprehension with tuple assignment
问题描述
我想问一下在python中是否可以进行这样的事情:
I want to ask if something like this is possible in python:
a,b = [i,i+1 for i in range(5)]
我知道这是不可能的,因为我遇到了错误,但是我认为您理解我正在努力实现的目标.让我清除它,我可以做到:
I know this isn't possible because I have got an error, but I think you understand what I am trying to achieve. Let me clear it up, I can do :
a,b = 3+2,3
编辑--->甚至更好:
Edit ---> Or even better:
a,b = [0,1,2,3,4],[1,2,3,4,5]
在我的第一个代码示例中,我不会做类似的事情.我正在尝试使用列表理解将变量"a"和"b"分配为列表,但是使用元组作为赋值,关键是我不想使用此变量:
I wan't a similar thing in my first code example. I am trying to assign variables 'a' and 'b' as list, with list comprehension, but using tuple as assignment, the point is I don't want to use this:
a = [i for in range(5)]
b = [i+1 for in range(5)]
我知道我可以使用它: t = [(i,i + 1)for range(5)中的i]
,但这不是重点.
顺便说一下,这只是一个简单的例子=>"i,i + 1"
I am aware that I can use this: t = [(i,i+1) for i in range(5)]
, but that's not the point.
By the way this is only a simple example => "i,i+1"
编辑--->我想澄清我的问题.如何使用列表推导在一行中分配多个变量(类型列表)?
Edit ---> I would like to clarify my question. How to assign several variables (type list) in one line, using list comprehension?
推荐答案
在运行此程序时:
a,b = [(i,i+1) for i in range(5)] # wrapped i, i+1 in parentheses (syntax error)
它列出了五个两个项的元组,如下所示:
It makes a list of five two-item tuples, like this:
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
但是您试图将这五个元组仅分配给两个对象( a
和 b
)
But you're trying to assign those five tuples to only two objects (a
and b
)
使用 zip 中的参数解压缩(*),您可以将输出解压缩到每个元组的第一和第二个元素:
Using argument unpacking (*) in zip, you can "unzip" the output to the first and second elements of each tuple:
a,b = zip(*[(i,i+1) for i in range(5)])
这是什么:
[(0, 1, 2, 3, 4), (1, 2, 3, 4, 5)]
并且可以在您编写时将其分配给 a
和 b
And can be assigned to a
and b
as you've written
这篇关于具有元组分配的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!