私の頭に浮かぶ最初のこと:
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