python - 如何快速查单?

标签 python list python-2.7 python-2.x

假设我有一个列表如下:

a = ['111', '222', '3334', '12']

当我只是检查一个元素,超过或少于 3 个长度时,它会返回错误并停止检测。

这是我的方法:

for b in a:
    if len(b) != 3:
        return False

但是它应该有更好的方法,怎么办?


它用于与anyall 讨论性能。 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/

相关文章:

python - 让代码变得更好 - 动态追加列表 DF

python - 排除位置以在 python 中创建新间隔

python - 如何使用 ffmpeg 从视频中获得前 16 个名声?

python - 优胜美地 : Python MySQLlib issue - 'no suitable image found'

java - 将列表中的对象转换为子类

python - 如何让 Python 的 multiprocessing Queue 的 .empty() 方法返回正确的值?还是替代品?

python - 从文件夹内的谷歌云存储下载文件

Python 写时复制行为

Python Tkinter : textfield enter command

python - Django CMS "No module named html5lib"