Python iter()时间复杂度? [英] Python iter() time complexity?

查看:175
本文介绍了Python iter()时间复杂度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种有效的方法来从Python集合中检索(任何)元素,并且遇到了这种方法:

I was looking up an efficient way to retrieve an (any) element from a set in Python and came across this method:

anyElement = next(iter(SET))

当从诸如set之类的容器中生成迭代器时,究竟发生了什么?它是否只是创建一个指向对象在内存中位置的指针,并在每次调用next时移动该指针?还是将集合转换为列表,然后在其中创建一个迭代器?

What exactly happens when you generate an iterator out of a container such as a set? Does it simply create a pointer to the location of the object in memory and move that pointer whenever next is called? Or does it convert the set to a list then create an iterator out of that?

我主要关心的是后者,看来iter()将是O(n)运算.到那时,最好从集合中弹出一个项目,将弹出的项目存储在变量中,然后将弹出的项目重新插入到集合中.

My main concern is if it were the latter, it seems iter() would be an O(n) operation. At that point it would be better to just pop an item from the set, store the popped item in a variable, then re-insert the popped item back into the set.

感谢您提前提供任何信息!

Thanks for any information in advance!

推荐答案

集合 是可迭代的,但是没有.__next__()方法,因此 iter()调用设置实例的.__iter__()方法,并返回

sets are iterable, but don't have a .__next__() method, so iter() is calling the .__iter__() method of the set instance, returning an iterable which does have the __next__ method.

由于这是O(1)调用的包装,因此一旦声明,它将在O(1)时间操作

As this is a wrapper around an O(1) call, it will operate in O(1) time once declared

https://wiki.python.org/moin/TimeComplexity

这篇关于Python iter()时间复杂度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆