python - 枚举 next() 不工作

python - enumerate next() not working

l = []
for i, obj in enumerate(queryset):
    if queryset[i].next():
        if queryset[i].common_id == queryset[i+1].common_id:
            l.append(queryset[i])

但我得到:

'MyModel' object has no attribute 'next'

但是 the docs 说:

The next() method of the iterator returned by enumerate() returns a tuple containing a count and the values obtained from iterating over sequence

我做错了什么?

你说的next()方法是针对enumerate返回的迭代器的。例如:

>>> someIterator = enumerate(range(5,10))
>>> tuple = someIterator.next()
>>> tuple
(0, 5)

执行for循环时,for循环每一步调用enumerate(...).next()。就像你在C里做for (i=0;i<10;i++)一样,在循环的核心,你不用再自增i

如果在你的循环中你只需要访问一些对象和下一个,你应该注意最后一步:

>>> l = range(5,10)
>>> for i, obj in enumerate(l):
...   print l[i],l[i+1]
...
5 6
6 7
7 8
8 9
9
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: list index out of range
>>>

而只使用范围:

>>> for i in range(len(l)-1):
...   print l[i],l[i+1]
...
5 6
6 7
7 8
8 9

因为在你的循环中,你无论如何都不使用 obj
您还可以特别注意最后一步:

>>> l = range(5,10)
>>> for i, obj in enumerate(l):
...   if i<len(l)-1:
...     print l[i],l[i+1]
...   else:
...     print l[i]
...
5 6
6 7
7 8
8 9
9

或者在 while 循环中使用迭代器(当没有项目时,next() 引发 StopIteration

>>> someIterator = enumerate("abcde")
>>> current = someIterator.next()
>>> try:
...     while someIterator:
...        nextOne = someIterator.next()
...        print current, nextOne
...        if current == nextOne:
...           pass#dosomething
...        current = nextOne
... except:
...     print "end of iteration", current
...
(0, 'a') (1, 'b')
(1, 'b') (2, 'c')
(2, 'c') (3, 'd')
(3, 'd') (4, 'e')
end of iteration (4, 'e')

可能更好的处理方法是在列表理解中使用 zip

l = [item for item, next_item in zip(queryset, queryset[1:])
         if item.common_id == next_item.common_id]