9

Can someone tell me how exactly Python's for loops are implemented? The reason I'm asking this is because I'm getting different behavior in the following two for loops when I expect the same behavior (assuming cases is just a set of elements):

First for loop:

for case in cases:
    blah

Second for loop:

for i in range(len(cases)):
    case = cases[i]
    blah

I'm running my code in a multi-threaded environment.

Basically, I'm wondering whether Python's for loop's iterating over a set (as in the first for loop) is simply a quickhand way of the second one. What exactly happens when we use the python for loop, and is there any underlying optimization/ implementation that may be causing the behavior difference I'm observing?

4

3 回答 3

18

不,第二种格式完全不同。

for循环调用iter()to-loop-over 序列,并使用next()对结果的调用。认为它相当于:

iterable = iter(cases):
while True:
    try:
        case = next(iterable)
    except StopIteration:
        break

    # blah

调用列表的结果iter()是一个列表迭代器对象:

>>> iter([])
<list_iterator object at 0x10fcc6a90>

该对象保留对原始列表的引用并跟踪它所在的索引。该索引从 0 开始并递增,直到列表被完全迭代。

不同的对象可以返回具有不同行为的不同迭代器。混入线程后,您最终可能会cases用其他东西替换,但迭代器仍会引用旧序列。

于 2013-05-05T18:11:26.673 回答
0
l = [1, 2, 3, 4, 5]
l = iter(l)
while True:
    try:
        print l.next()
    except StopIteration:
        exit()
于 2020-03-05T05:53:39.603 回答
-2

我没有得到任何区别,请在下面查看,您是否正在尝试..

>>> cases = [1,2,3]
>>> for case in cases:
...     print case
...
1
2
3
>>> i=0
>>> for i in range(len(cases)):
...     print cases[i]
...
1
2
3
>>>
于 2013-05-05T18:25:22.373 回答