简体   繁体   English

将变量分配给整个可迭代对象,同时在 for 循环中执行可迭代对象解包

[英]Assign variable to entire iterable while simultaneously performing Iterable unpacking in for loop

Is there a way, using Extended Iterable Unpacking , in a loop to assign multiple values within an iterable as well as a variable holding all of the iterable.有没有办法,使用Extended Iterable Unpacking ,在循环中在一个迭代中分配多个值以及一个保存所有迭代的变量。

This is possible not in a loop using:这可能不是在循环中使用:

abc = a, b, c = range(3)

But in a loop I don't know of a syntactically equivalent option.但是在循环中,我不知道语法上等效的选项。 Currently I would use:目前我会使用:

it = zip(*[iter(range(9))]*3) #for example

for abc in it:
    a, b, c = abc
    ...

Or this:或这个:

for a, b, c in it:
    abc = [a, b, c]
    ...

I want to know if there is a way to have the best of both worlds here.我想知道是否有办法在这里两全其美。 Something along the lines of the following (which is not valid although an example of what I mean) :类似于以下内容(尽管我的意思是一个例子,但这是无效的)

for (a, b, c := abc) in it:
    ...

The closest you can get, due to the constraints on where an assignment expression is allowed, is由于允许赋值表达式的限制,您可以获得的最接近的是

for a, b, c in (abc := x for x in it):
    ...

x is bound to the "scope" of the generator expressions, but abc is bound in the scope containing the generator expression, ie, the same scope in which a , b , and c are bound. x绑定到生成器表达式的“范围”,但abc绑定在包含生成器表达式的范围内,即与abc绑定的范围相同。

If I saw anyone doing this in a code review, though, I'd tell them to just write但是,如果我在代码审查中看到有人这样做,我会告诉他们只写

for abc in it:
    a, b, c = abc
    ...

if they really need all four names defined.如果他们真的需要定义所有四个名称。

Although this does answer my question there would likely be added overhead, and to me it is just unnecessary extra code.虽然这确实回答了我的问题,但可能会增加开销,对我来说这只是不必要的额外代码。

from itertools import tee

for abc, (a, b, c) in zip(*tee(it)):
    …

You could do this:你可以这样做:

for *abc,a,b,c in (x*2 for x in it):
    print(abc,a,b,c)

(0, 1, 2) 0 1 2
(3, 4, 5) 3 4 5
(6, 7, 8) 6 7 8

Or have abc predefined outside the scope of the comprehension:或者在理解范围之外预定义 abc:

abc = []
for a,b,c in (abc:=x for x in it):
    print(abc,a,b,c)

(0, 1, 2) 0 1 2
(3, 4, 5) 3 4 5
(6, 7, 8) 6 7 8

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

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