简体   繁体   English

某些PEP是否为内置序列类型保证了len(...)的O(1)复杂度?

[英]Is O(1) complexity of len(…) guaranteed by some PEP for built-in sequence types?

Many questions about cost of len(...) are answered but I haven't found any link to Python documentation. 关于len(...)成本的许多问题都得到了解答,但我没有找到任何Python文档的链接。

Is it by standard (documented in some PEP) or just way how it's currently implemented in most Python implementations? 它是通过标准(在某些PEP中记录)还是在大多数Python实现中如何实现?

Documentation about time complexity for certain built-in python objects is here . 关于时间的某些内置Python对象的复杂文档是在这里

The len() function in python just calls the __len__ method in your class. python中的len()函数只调用类中的__len__方法。 So if you built a custom class 所以如果你构建了一个自定义类

class SlowLenList(object):

  def __init__(self, mylist):
    self.mylist = mylist

  def __len__(self):
    total = 1
    for item in self.mylist:
      total += 1
    return total

Then the complexity would be O(n) in this case. 那么在这种情况下复杂度将是O(n)。 So it really depends on the object you are calling. 所以它真的取决于你所呼唤的对象。 I assume the built-in list and other objects are O(1) because they have an attribute on an instance that increments every time an item is added to the object. 我假设内置列表和其他对象是O(1),因为它们在实例上有一个属性,每次将项添加到对象时它都会递增。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM