Python 迭代器:iglob() 的迭代器在 glob() 的列表上提供了什么?

发布于 2024-10-04 13:30:51 字数 648 浏览 0 评论 0原文

给出一段代码:

from glob import glob, iglob

for fn in glob('/*'):
    print fn

print ''

for fn in iglob('/*'):
    print fn

阅读 glob文档 ,我看到 glob() 返回一个基本的文件列表,而 iglob 则返回一个 Iterator。但是,我可以迭代这两个文件,并且每个文件都返回相同的文件列表。

我已阅读有关 Iterator 的文档,但它并没有真正阐明这个主题!

那么,通过 glob() 返回 Iterator 为我提供的列表相比,iglob() 有什么好处呢?我是否比我的老朋友低级列表获得了额外的功能?

Given the piece of code:

from glob import glob, iglob

for fn in glob('/*'):
    print fn

print ''

for fn in iglob('/*'):
    print fn

Reading the documentation for glob, I see that glob() returns a basic list of files and iglob an Iterator. However, I'm able to iterate over both and the same list of files is returned by each of them.

I've read the documentation on Iterator, but it hasn't shed anymore light on the subject really!

So what benefit does iglob() returning an Iterator provide me over the list from glob()? Do I gain extra functionality over my old friend the lowly list?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吃兔兔 2024-10-11 13:30:51

文档本身提到了差异:

返回一个迭代器,它产生与 glob() 相同的值,而无需实际同时存储它们。

基本上列表将包含内存中的所有项目。迭代器不需要,因此它需要更少的内存。

The difference is mentioned in the documentation itself:

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

Basically list will have all the items in memory. Iterator need not, and hence it requires less memory.

很糊涂小朋友 2024-10-11 13:30:51

添加到 amit 的答案iglob() 在特定情况下很有用,如果删除列表中的目录,列表中的文件和文件夹将由 glob() 存储,因此进一步循环中的访问会抛出异常。但是通过使用iglob(),我们可以克服并发修改异常

Adding to amit's answer. iglob() is useful in the particular case where if you delete a directory in the list, the files and folders in the list will be stored by glob() and hence further access in the loop throws exception. But by using iglob() we can overcome the concurrent modification exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文