【问题标题】:Attribute Error: next()属性错误:next()
【发布时间】:2013-08-31 11:57:13
【问题描述】:

我想使用next() 和os.walk 循环一层深度

我的代码的关键行:

for root, dirs, files in os.walk(dir).next(1): 

错误:

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

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

【问题讨论】:

  • 您为什么要使用.next(1) 或.next()[1] 根本?您在这里的 for 循环中使用了生成器;是否只想使用 dirs 值?

标签: python


【解决方案1】:

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

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

>>> L = (x for x in range(10))
>>> next(L)
0
>>> next(L)
1

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

然而,在您的代码中调用next 根本没有意义。你想用它来达到什么目的?

在做:

for root, dirs, files in next(os.walk(dir)):

将引发错误,因为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:
   #...

如果您只想在目录上进行迭代,正如 Martijn 推测的那样,那么您不必特别做任何事情。不要在循环中使用root 和files 变量。在这种情况下,我建议将它们重命名为 _,这通常用于表示我们必须分配但根本不使用的变量:

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

如果您想使用可迭代的第一个 n 元素,您可以使用 itertools.islice 和 collections.deque 快速完成,并且不消耗内存:

from itertools import islice
from collections import deque

def drop_n_elements(n, iterable):
    deque(islice(iterable, n), maxlen=0)

然后将其用作:

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

我突然想到有一种更快、更简单的方法来删除可迭代的前 n 个元素:

def drop_n_elements(n, iterable):
    next(islice(iterable, n, n), None)

它比使用deque(..., maxlen=0) 稍微快一些,因为它只调用islice 的next 方法。

【讨论】:

  • 感谢您的全面回答。作为初学者,它肯定会对我有很大帮助。
  • 还有一个问题。是否可以反转最后一个函数(islice)?实际使用前 N 次迭代并丢弃更深层次?
  • @BikerJohn 当然。只需执行for element in islice(iterable, n)。 islice 像 slices 在列表中一样工作。 drop_n_elements 只是使用islice 获取前n 个元素并使用deque 将它们丢弃。查看islice 的文档以获取更多信息。
  • @BikerJohn 我突然想到,当丢弃元素时,你可以完全避免使用deque。
  • 太好了,这正是我所需要的。再次感谢:)
【解决方案2】:
for root, dirs, files in os.walk(dir).__next__()[1]:

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2022-07-01
    • 2014-02-28
    相关资源
    最近更新 更多