属性错误:next()

Bik*_*ohn 7 python

我想使用next()with 循环一个深度os.walk

我的代码的关键行:

for root, dirs, files in os.walk(dir).next(1): 
Run Code Online (Sandbox Code Playgroud)

错误:

AttributeError:'generator'对象没有属性'next'

我尝试使用社区建议.next(x)替换旧的next()[1],但这也不起作用.

Bak*_*riu 19

您正在使用python3.在python3中,该next()方法被替换为__next__.这些方法接受任何参数(即a.__next__(1)错误).他们将迭代器推进一个.通过更多元素next反复调用来推进它.

如果你想通过一次使用推进迭代器,我建议使用next内置函数:

>>> L = (x for x in range(10))
>>> next(L)
0
>>> next(L)
1
Run Code Online (Sandbox Code Playgroud)

注意:next我相信内置函数是在python2.6中添加的,所以即使在python2中也可以使用它.

但是,在你的代码中,根本没有任何意义next.你想用它做什么?

这样做:

for root, dirs, files in next(os.walk(dir)):
Run Code Online (Sandbox Code Playgroud)

将引发错误,因为next返回第一个元素os.walk,它是一个包含字符串列表的三元素元组.但for循环将遍历元组,尝试将单个列表解压缩root, dirs, files.如果任何目录包含多于或少于3个文件/子目录,则代码将失败.

如果您只想跳过第一个目录,则必须next单独调用:

iterable = os.walk(directory)
next(iterable)   # throw away first iteration
for root, dirs, files in iterable:
   #...
Run Code Online (Sandbox Code Playgroud)

如果你想只根据Martijn推测的目录进行迭代,那么你就不必特别做任何事情了.只是不要在循环中使用rootfiles变量.在这种情况下,我建议将它们重命名为_,通常用于指示我们必须分配的变量,但根本不使用它:

for _, dirs, _ in os.walk(directory):
    # Work only on "dirs". Don't care for "_"s
Run Code Online (Sandbox Code Playgroud)

如果你想使用niterable 的第一个元素,你可以使用itertools.islicecollections.deque快速执行它而不消耗内存:

from itertools import islice
from collections import deque

def drop_n_elements(n, iterable):
    deque(islice(iterable, n), maxlen=0)
Run Code Online (Sandbox Code Playgroud)

然后将其用作:

iterable = os.walk(directory)
drop_n_elements(N, iterable) # throw away first N iterations
for root, dirs, files in iterable:
    # ...
Run Code Online (Sandbox Code Playgroud)

我刚想到有一种更快更容易的方法来删除迭代的前n个元素:

def drop_n_elements(n, iterable):
    next(islice(iterable, n, n), None)
Run Code Online (Sandbox Code Playgroud)

它比使用稍快,deque(..., maxlen=0)因为它只对一个next方法进行一次调用islice.