简体   繁体   English

访问元组中元素的时间复杂度

[英]Time complexity of accessing an element in a tuple

There is similar question about hash (dictionaries) and lists, also there is a good piece of info here: http://wiki.python.org/moin/TimeComplexity关于 hash (字典)和列表有类似的问题,这里也有一个很好的信息: http://wiki.python.org/moin/TimeComplexity

But I didn't find anything about tuples.但我没有找到任何关于元组的信息。

The access time for访问时间为

data_structure[i]
  • for a linked list is in general O(n)对于链表,通常是 O(n)
  • for dictionary is ~ O(1)对于字典是〜O(1)

What about tuple?元组呢? Is it O(n) like for a linked list or O(1) like for an array?链表是 O(n) 还是数组是 O(1)?

It's O(1) for both list and tuple.列表和元组都是 O(1)。 They are both morally equivalent to an integer indexed array.它们在道德上都等同于 integer 索引数组。

Lists and tuples are indexable in the exact same way arrays are in other languages.列表和元组的索引方式与 arrays 在其他语言中的方式完全相同。

A simplified explanation is that space is allocated for references to objects, those references take up a uniform amount of space, and any index is simply multiplied by the size of the reference to get an offset into the array.一个简化的解释是,空间是为对象的引用分配的,这些引用占用相同数量的空间,并且任何索引都简单地乘以引用的大小以获得数组的偏移量。 This gives constant, O(1), access for lists and tuples.这为列表和元组提供了常量 O(1) 访问权限。

Getting an item from a linked-list is O(n), but Python lists have array-based implementations so the cost is O(1).从链表中获取项目是 O(n),但 Python 列表具有基于数组的实现,因此成本是 O(1)。

Tuples are also implemented using arrays so it's O(1) for them too.元组也是使用 arrays 实现的,所以对它们来说也是 O(1)。

It should be O(1) , because it really is only a list.它应该是O(1) ,因为它实际上只是一个列表。

But for python lists, I'd expect O(1) too.但是对于 python 列表,我也希望O(1) You might want to think about it again...你可能想再考虑一下...

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

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