python中index函数_列表中的in和index函数[Python]

好问题!是的,你提到的两种方法都必须遍历列表. Python不使用列表的哈希表,因为列表元素是不可限制的.

如果您知道约“Big O” notation,列表数据结构是通过查找已知索引(例如, my_list [13].会员考试是O(n).

还有其他数据结构针对成员身份测试(即__contains__)的O(1)速度进行了优化,即set和dict.这些都是用hashtables实现的.

以下是一个示例,说明如何使用IPython验证time-complexity的集合和列表,以确认这些声明:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值