循环的 Python 列表理解

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18649884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:21:05  来源:igfitidea点击:

Python list comprehension for loops

pythonfor-looplist-comprehension

提问by ChandlerQ

I'm reading the Python wikibookand feel confused about this part:

我正在阅读Python wikibook并对此部分感到困惑:

List comprehension supports more than one for statement. It will evaluate the items in all of the objects sequentially and will loop over the shorter objects if one object is longer than the rest.

>>>item = [x+y for x in 'cat' for y in 'pot']
>>>print item
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']

列表理解支持多个 for 语句。它将按顺序评估所有对象中的项目,如果一个对象比其他对象长,它将遍历较短的对象。

>>>item = [x+y for x in 'cat' for y in 'pot']
>>>print item
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']

I understand the usage of nested for loops but I don't get

我了解嵌套 for 循环的用法,但我不明白

...and will loop over the shorter objects if one object is longer than the rest

...如果一个对象比其他对象长,则会遍历较短的对象

What does this mean? (shorter, longer...)

这是什么意思?(更短,更长...)

采纳答案by dawg

These type of nested loops create a Cartesian Productof the two sequences. Try it:

这些类型的嵌套循环创建两个序列的笛卡尔积。尝试一下:

>>> [x+y for x in 'cat' for y in 'potty']
['cp', 'co', 'ct', 'ct', 'cy', 'ap', 'ao', 'at', 'at', 'ay', 'tp', 'to', 'tt', 'tt', 'ty']
>>> [x+y for x in 'catty' for y in 'pot']
['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt', 'tp', 'to', 'tt', 'yp', 'yo', 'yt']

The inner'x' in the list comprehension above (ie, the for x in 'cat'part) the is the same as the outerfor x in 'cat':in this example:

上面列表推导式中的内部“x”(即for x in 'cat'部分)与本示例中的外部相同for x in 'cat':

>>> li=[]
>>> for x in 'cat':
...    for y in 'pot':
...       li.append(x+y)
# li=['cp', 'co', 'ct', 'ap', 'ao', 'at', 'tp', 'to', 'tt']

So the effect of making one shorter or longer is the same as making the 'x' or 'y' loop longer in two nested loops:

因此,缩短或延长一个循环的效果与在两个嵌套循环中延长 'x' 或 'y' 循环的效果相同:

>>> li=[]
>>> for x in 'catty':
...    for y in 'pot':
...       li.append(x+y)
... 
>>> li==[x+y for x in 'catty' for y in 'pot']
True

In each case, the shorter sequence is looped over again until the longer sequence is exhausted. This unlike zipwhere the pairing would be terminated at the end of the shorter sequence.

在每种情况下,较短的序列都会再次循环,直到用完较长的序列。这与zip配对将在较短序列的末尾终止的情况不同。

Edit

编辑

There seems to be confusion (in the comments) about nested loops versus zip.

关于嵌套循环与 zip 似乎存在混淆(在评论中)。

Nested Loops:

嵌套循环:

As shown above, this:

如上所示,这个:

[x+y for x in '12345' for y in 'abc']

is the same as two nested 'for' loops with 'x' the outer loop.

与两个嵌套的“for”循环相同,“x”是外循环。

Nested loops will execute the inner yloop the range of xin the outer loop times.

嵌套循环将在外循环次数y的范围内执行内循环x

So:

所以:

>>> [x+y for x in '12345' for y in 'ab']
    ['1a', '1b',   # '1' in the x loop
     '2a', '2b',   # '2' in the x loop, b in the y loop
     '3a', '3b',   # '3' in the x loop, back to 'a' in the y loop
     '4a', '4b',   # so on
     '5a', '5b'] 

You can get the same result with productfrom itertools:

您可以从 itertools获得与product相同的结果:

>>> from itertools import product
>>> [x+y for x,y in product('12345','ab')]
['1a', '1b', '2a', '2b', '3a', '3b', '4a', '4b', '5a', '5b']

Zip is similarbut stops after the shorter sequence is exhausted:

Zip类似,但在较短的序列用完后停止:

>>> [x+y for x,y in zip('12345','ab')]
['1a', '2b']
>>> [x+y for x,y in zip('ab', '12345')]
['a1', 'b2']

You can use itertoolsfor a zip that will zip until the longest sequence is exhausted, but the result is different:

您可以对 zip使用itertools,该 zip 将一直压缩直到用完最长序列,但结果不同:

>>> import itertools
>>> [x+y for x,y in itertools.zip_longest('12345','ab',fillvalue='*')]
['1a', '2b', '3*', '4*', '5*'] 

回答by Manoj Pandey

Well, the Python documentation does not talk of any such short/long case: http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions. Having two "for" in a list comprehension means having two loops. The example pointed by @drewk is correct.

好吧,Python 文档没有讨论任何这样的短/长案例:http: //docs.python.org/2/tutorial/datastructures.html#list-comprehensions。列表推导式中有两个“for”意味着有两个循环。@drewk 指出的例子是正确的。

Let me copy it for the sake of explanation:

为了说明起见,让我复制一下:

>>> [x+y for x in '123' for y in 'pot']
['1p', '1o', '1t', '2p', '2o', '2t', '3p', '3o', '3t']
>>>
>>> [x+y for x in '1' for y in 'pot']
['1p', '1o', '1t']
>>>

In both cases, the first "for" forms the outer loop and hte second "for" forms the inner loop. That is the only invariant here.

在这两种情况下,第一个“for”形成外循环,第二个“for”形成内循环。这是这里唯一的不变量。