枚举 next() 不起作用


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'

但文档说:

枚举() 返回的迭代器的 next() 方法返回一个 包含计数和 通过迭代序列获得的值

我做错了什么?

您正在谈论的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]

最新更新