Python "if len(A) is not 0" vs "if A" 语句



我的同事在条件下使用这种方式

if len(A) is not 0:
    print('A is not empty')

我更喜欢这个

if A:
    print('A is not empty')

什么是道具缺点参数?

的观点是,第一种方法是更直接的方式来展示她到底想要什么。我的观点是我的方式更短。

第一种方式也比我的快 2 倍:

>>> import timeit
>>> timeit.timeit('len(A) is not 0', setup='A=[1,2,3]')
0.048459101999924314
>>> timeit.timeit('bool(A)', setup='A=[1,2,3]')
0.09833707799998592

>>> import timeit
>>> timeit.timeit('if len(A) is not 0:n  pass', setup='A=[1,2,3]')
0.06600062699999398
>>> timeit.timeit('if A:n  pass', setup='A=[1,2,3]')
0.011816206999810674 

第二种方式快 6 倍!我很困惑if是如何工作的:-)

PEP 8 风格指南对此很清楚:

对于序列(字符串、列表、元组),请使用空的事实 序列是错误的。

Yes: if not seq:
     if seq:
No:  if len(seq):
     if not len(seq):
我认为

如果A = 42,您的同事代码会引发错误

object of type 'int' has no len()

而您的代码只会执行 if 之后的任何内容。

1.

if len(A) is not 0:
    print('A is not empty')

阿拉伯数字。

if A:
    print('A is not empty')

第一种方式和第二种方式之间的区别在于,您只能将len(A)用于列表,元组,字典等结构,因为它们支持len()功能,但不能将len()功能用于数据或类似字符,字符串,整数(数字)。

例如:

len(123), len(abc), len(123abc) : 将引发错误。

但 列表 = [1,2,3,4,5]

len(list) 不会引发错误

if A:
    statement  # this is useful while our only concern is that the variable A has some value or not 

你不是在比较同一件事。如果比较这个:

import timeit
print(timeit.timeit('if len(A) is not 0:n  pass', setup='A=[1,2,3]'))
print(timeit.timeit('if A:n  pass', setup='A=[1,2,3]'))

您将看到您的方法更快。另外,您的方法是一种更pythonic的方式。

最新更新