进入我脑海的第一件事:
all(e['type'] == L[0]['type'] for e in L)
类型集的长度:
len(set(e['type'] for e in L)) == 1
比all
使用生成器更有效,但不是使用列表:
>>> %timeit all(e['type'] == l[0]['type'] for e in l)
1000000 loops, best of 3: 784 ns per loop
>>> %timeit len(set(e['type'] for e in l)) == 1
1000000 loops, best of 3: 676 ns per loop
>>> %timeit all([e['type'] == l[0]['type'] for e in l])
1000000 loops, best of 3: 602 ns per loop
使用缓存l[0]['type']
:
>>> t1 = l[0]['type']
>>> %timeit all([e['type'] == t1 for e in l])
1000000 loops, best of 3: 447 ns per loop
>>> %timeit all(e['type'] == t1 for e in l)
1000000 loops, best of 3: 655 ns per loop
set
使用 list-comp 甚至比使用genexpr 更慢:
>>> %timeit len(set([gettype(e) for e in l])) == 1
1000000 loops, best of 3: 735 ns per loop
set
当没有短路的可能性时,我想到了另一种更快的方法:
>>> %timeit [e['type'] for e in l].count(t1) == len(l)
1000000 loops, best of 3: 421 ns per loop
另一个编辑:显然最直接的方法是最快的:
In [31]: def same_type(L):
....: t1 = L[0]['type']
....: for e in L:
....: if e['type'] != t1:
....: return False
....: return True
....:
In [32]: %timeit same_type(l)
1000000 loops, best of 3: 352 ns per loop
同类型长输入(无短路)
In [47]: l = [{'type': 1} for _ in range(1000)]
In [48]: %timeit same_type(l)
10000 loops, best of 3: 37.6 us per loop
In [49]: %timeit all(e['type'] == l[0]['type'] for e in l)
10000 loops, best of 3: 112 us per loop
In [50]: %timeit all([e['type'] == l[0]['type'] for e in l])
10000 loops, best of 3: 103 us per loop
In [51]: %timeit len(set(e['type'] for e in l)) == 1
10000 loops, best of 3: 63.3 us per loop
不同类型的长输入(立即短路)
In [40]: l = [{'type': x} for x in range(1000)]
In [43]: %timeit same_type(l)
1000000 loops, best of 3: 337 ns per loop
In [44]: %timeit all(e['type'] == l[0]['type'] for e in l)
1000000 loops, best of 3: 656 ns per loop
In [45]: %timeit all([e['type'] == l[0]['type'] for e in l])
10000 loops, best of 3: 99.4 us per loop
In [46]: %timeit len(set(e['type'] for e in l)) == 1
10000 loops, best of 3: 68.6 us per loop