让我们说:
x= [2,2,2,2]
y= [2,1,2,2]
Run Code Online (Sandbox Code Playgroud)
是否有任何简洁的方法来检查列表项是否全部相等.所以,我希望输出为:
x True
y False
Run Code Online (Sandbox Code Playgroud)
如果您关心性能并且列表可能很长:
all(item == x[0] for item in x)
Run Code Online (Sandbox Code Playgroud)
一旦找到不相等的元素,它就会完成.请注意all返回True空序列,因此如果不是您想要的结果,则len(x)先测试.
Timings,故意操纵的案件支持我的回答:
$ python --version
Python 2.7.5
$ python -mtimeit "x = range(1000000)"
10 loops, best of 3: 18 msec per loop
$ python -mtimeit "x = range(1000000); all(item == x[0] for item in x)"
100 loops, best of 3: 19.2 msec per loop
$ python -mtimeit "x = range(1000000); all(item == x[0] for item in x[1:])"
10 loops, best of 3: 35.6 msec per loop
$ python -mtimeit "x = range(1000000); len(set(x)) == 1"
10 loops, best of 3: 72.7 msec per loop
Run Code Online (Sandbox Code Playgroud)
通过"一点点",我只是意味着采取简单的步骤,以避免可能的大量不必要的工作和内存使用.如果你非常关心性能,因为这行代码非常关键,那么你可以做些什么来调整我的答案.首先想到的是避免在元素0处进行自我比较,但我不知道是否itertools.islice有足够低的开销来获得净胜利.你必须测试它.
好吧,你可以使用set:
>>> len(set(x)) == 1
True
>>> len(set(y)) == 1
False
Run Code Online (Sandbox Code Playgroud)
使用以下脚本查看,哪种方式最适合您:
from timeit import timeit
# All the same
print timeit('len(set([2, 2, 2, 2])) == 1')
# 0.843292317054
# Not the same
print timeit('len(set([2, 1, 2, 2])) == 1')
# 0.869108628247
## Without set ##
# AlL the same
print timeit('all(item == x[0] for item in x)', setup='x = [2,2,2,2]')
# 1.20339177387
# Not the same
print timeit('all(item == x[0] for item in x)', setup='x = [2, 1, 2, 2]')
# 1.42827283125
Run Code Online (Sandbox Code Playgroud)
根据我的经验,使用set似乎是最快的方式.
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |