列表中的in和index函数[Python] [英] in and index function of list [Python]
问题描述
我正在努力了解 c $ c>中的内部工作,列表数据结构的
index()
当我说:
if something not in some_list :
print "do something"
是否在内部遍历整个列表,类似于为
循环或使用,更好的方法,如 hashtables
等。
Is it traversing the whole list internally, similar to a for
loop or does it use, better approaches like hashtables
etc.
此外,列表中的 index()
也会在列表中不存在该项。在和 index()
中的的工作是一样的吗?如果
index()
更好的是,当一个项目不存在时,是否有可能捕获错误,如果可能,它是否是很好的编程?
Also the index()
in lists, gives an error if the item is not present in the list. Is the working of both in
and index()
the same? If index()
is better then is it possible to catch the error when an item is not present and if it is possible, is it good programming?
推荐答案
好问题!是的,你提到的两种方法都必须遍历列表。 Python不会为列表使用散列表,因为列表元素不可限制。
Good question! Yes, both methods you mention will iterate the list, necessarily. Python does not use hashtables for lists because there is no restriction that the list elements are hashable.
如果您了解大写符号,列表
数据结构是为O(1)访问而设计的通过查找已知的索引,例如 my_list [13]
。会员考试是O(n)。
If you know about "Big O" notation, the list
data structure is designed for O(1) access by looking up a known index, e.g. my_list[13]
. It is O(n) for membership testing.
还有其他针对O(1)速度进行成员身份测试的数据结构(即 __包含__
),即 set
和 dict
。这些都是通过哈希表实现的。
There are other data structures which are optimised for O(1) speed for membership testing (i.e. __contains__
), namely set
and dict
. These are implemented with hashtables.
以下是使用 IPython
验证时间复杂度的集合和列表,以确认这些声明:
Here is an example of how you can use IPython
to verify the time-complexity of sets and lists, to confirm these claims:
In [1]: short_list, long_list = range(1000), range(10000)
In [2]: timeit 'potato' not in short_list
10000 loops, best of 3: 40.9 µs per loop
In [3]: timeit 'potato' not in long_list
1000 loops, best of 3: 440 µs per loop
In [4]: small_set, big_set = set(short_list), set(long_list)
In [5]: timeit 'potato' not in small_set
10000000 loops, best of 3: 72.9 ns per loop
In [6]: timeit 'potato' not in big_set
10000000 loops, best of 3: 84.5 ns per loop
这篇关于列表中的in和index函数[Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!