假设我有一个列表如下:
a = ['111', '222', '3334', '12']
当我只是检查一个元素,超过或少于 3 个长度时,它会返回错误并停止检测。
这是我的方法:
for b in a:
if len(b) != 3:
return False
但是它应该有更好的方法,怎么办?
它用于与any
和all
讨论性能。 sureshv 提到 any
优于 all
但我使用 timeit
证明 all
优于 any
。但是,not all(...)
可以忽略,not
的性能开销很大。
from timeit import timeit
print timeit('any(len(x) != 3 for x in ["111", "222", "3334", "12", "111", "222" , "111", "222" , "111", "222"])', number=100000)
print timeit('all(len(b) == 3 for b in ["111", "222", "3334", "12", "111", "222" , "111", "222" , "111", "222"])', number=100000)
print timeit('not all(len(b) == 3 for b in ["111", "222", "3334", "12", "111", "222" , "111", "222" , "111", "222"])', number=100000)
>>>first
0.0830238555881
0.0820391147939
0.0863792158681
>>>second
0.0826572149797
0.0818332714663
0.0830155876428
>>>third
0.0836901379378
0.0809026999688
0.0812479579601
最佳答案
我想你正在寻找:
if any(len(x) != 3 for x in a):
return False
关于python - 如何快速查单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009416/