[英]What is the complexity of index for lists of lists(e.g. list[x][y])
In python 在python中
lst = [[1,2,3...],[4,5,6...]]
Assume I have a list whose length is n
and each nested list has the same length. 假设我有一个长度为
n
的列表,每个嵌套列表的长度都相同。 So I want to use lst[x][y]
to find some element. 所以我想用
lst[x][y]
查找一些元素。 what is the complexity of it? 它的复杂性是什么? I tried to google it but not find answers.
我试图用谷歌搜索,但没有找到答案。
Edited:Thanks guys! 编辑:谢谢大家! So if I input a list containing n lists (each containing n elements), then how many times do I index the list (in terms of n)?
因此,如果我输入一个包含n个列表的列表(每个列表包含n个元素),那么该索引列表多少次(以n表示)? Is it 2n?
是2n吗?
Time complexity of Python data structures are documented here: Python数据结构的时间复杂性在此处记录:
https://wiki.python.org/moin/TimeComplexity https://wiki.python.org/moin/TimeComplexity
The one you're asking about is "Get Item" for list
, and it's O(1) . 您要询问的是“获取项目”
list
,它是O(1) 。 Even though you index a list and a nested list, that's still O(1) . 即使您为列表和嵌套列表建立索引,它仍然是O(1) 。
Indexing is an O(1) operation (constant time). 索引是O(1)操作(恒定时间)。 Thus, two successive indexing operations is still O(1) .
因此,两个连续的索引操作仍为O(1) 。
This page shows that "get item" is O(1)
. 此页面显示“获取项目”为
O(1)
。 To analyze an expression like l[x][y]
it might be helpful to break it into its components: 要分析像
l[x][y]
这样的表达式,将其分解成各个部分可能会有所帮助:
temp = l[x]
temp[y]
When analyzing sequential operations, we add the time complexity. 在分析顺序操作时,我们增加了时间复杂度。 So this is
O(1) + O(1)
. 所以这是
O(1) + O(1)
。 But this simplifies to just O(1)
. 但这简化为
O(1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.