序列空检查的len()和pep8建议的成本

Kor*_*maz 3 python pep8

如果python的复杂性len()是O(1),为什么pep8建议使用 if seq:而不是if len(seq) == 0:

https://wiki.python.org/moin/TimeComplexity
https://www.python.org/dev/peps/pep-0008/#programming-recommendations

不是len(seq) == 0更具可读性吗?

Cor*_*mer 8

前者可以处理空字符串和None.例如,考虑这两个变量.

>>> s1 = ''
>>> s2 = None
Run Code Online (Sandbox Code Playgroud)

使用第一种方法

def test(s):
    if s:
        return True
    else:
        return False

>>> test(s1)
False
>>> test(s2)
False
Run Code Online (Sandbox Code Playgroud)

现在用 len

def test(s):
    if len(s) == 0:
        return True
    else:
        return False

>>> test(s1)
True
>>> test(s2)
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    test(s2)
  File "<pyshell#11>", line 2, in test
    if len(s) == 0:
TypeError: object of type 'NoneType' has no len()
Run Code Online (Sandbox Code Playgroud)

所以在性能方面,两者都是O(1),但真实性测试(第一种方法)更加健壮,因为它None除了处理空字符串外还处理.

  • @SomethingSomething绝对.事实上,这个答案中的观察是没有用的.在实际代码中,当您检查序列是空还是不为空时,因为您希望对其执行某些操作(例如索引,追加,删除等).那些不适用于"无"无论如何使这种观察在99%的情况下无用.使用`seq is/is not None`,剩余的0.99%会更清晰. (3认同)

Bak*_*riu 5

O(1)的事实len只是一个约定。可能存在不是 O(1) 的序列/集合,len此时检查可能len(x) == 0 花费更多时间。

事实是:问题“这个集合的大小等于吗k?” 和“集合是空的吗?” 是根本不同的问题。第一个由[ie is true] 回答len(x) == k,后者由bool(x)[ie is xtrue] 回答。因此,如果你想检查集合是否为空,你只需使用if collection. 它们只是碰巧重合,如果k == 0

一般来说,您应该使用最具体的术语来准确描述您正在做的事情。写作len(x) == 0可能只是一个错字,len(x) == 10漏掉了,1而写错if x就更难了。