编程语言
首页 > 编程语言> > Python的’in’效率/速度有多快? (明智的时间复杂性)

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