python速度比较_Python的’in’效率/速度有多快? (明智的时间复杂性)

在Python中,in关键字的效率是多少,例如:

a = [1, 2, 3]

if 4 in a:

...

解决方法:

这取决于右手operand:

The operators in and not in test for collection membership. […] The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.

类可以实现special method __contains__以覆盖默认行为(迭代序列),因此可以提供更多(或更少)有效的方法来测试成员资格,而不是比较容器的每个元素.

The membership test operators (in and not in) are normally implemented as an iteration through a sequence. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be a sequence.

由于您的示例中有一个列表,因此会对其进行迭代,并比较每个元素,直到找到匹配项或列表用尽为止.时间复杂度通常为O(n).

标签:python,performance,time-complexity,operator-keyword

来源: https://codeday.me/bug/20190928/1826763.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值