简体   繁体   English

列表理解与元组赋值

[英]List comprehension with tuple assignment

I want to ask if something like this is possible in python: 我想问一下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]

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'和'b'分配为列表,使用列表理解,但使用元组作为赋值,重点是我不想使用它:

a = [i for in range(5)]
b = [i+1 for in range(5)]

I am aware that I can use this: t = [(i,i+1) for i in range(5)] , but that's not the point. 我知道我可以使用这个: t = [(i,i+1) for i in range(5)] ,但那不是重点。
By the way this is only a simple example => "i,i+1" 顺便说一下这只是一个简单的例子=>“i,i + 1”

Edit ---> I would like to clarify my question. 编辑--->我想澄清一下我的问题。 How to assign several variables (type list) in one line, using list comprehension? 如何使用列表推导在一行中分配多个变量(类型列表)?

When you run this: 当你运行这个:

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)]

But you're trying to assign those five tuples to only two objects ( a and b ) 但是你试图将这五个元组分配给两个对象( ab

Using argument unpacking (*) in zip , you can "unzip" the output to the first and second elements of each tuple: zip中使用参数解包(*),您可以将输出“解压缩”到每个元组的第一个和第二个元素:

a,b = zip(*[(i,i+1) for i in range(5)])

Which is this: 这是:

[(0, 1, 2, 3, 4), (1, 2, 3, 4, 5)]

And can be assigned to a and b as you've written 并且可以像你写的那样分配到ab

Don't try to be clever. 不要试图聪明。 This is perfectly acceptable code: 这是完全可以接受的代码:

>>> a = range(5)
>>> b = range(1,6)
>>> a, b
([0, 1, 2, 3, 4], [1, 2, 3, 4, 5])

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

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