我在列表中嵌套了元组
l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')]
我想知道列表中总共有多少个“a”和“b”。所以我目前使用以下代码来获取结果。
amount_a_and_b = len([None for _, elem2, elem3 in l if elem2 == 'a' or elem3 == 'b'])
但是我得到了amount_a_and_b = 1,那么如何得到正确的答案呢?
此外,是否有更优雅的方式(更少的代码或更高的性能或使用内置函数)来做到这一点?
请您参考如下方法:
我会用 itertools.chain.from_iterable() 将列表展平并将其传递给 collections.Counter() object :
from collections import Counter
from itertools import chain
counts = Counter(chain.from_iterable(l))
amount_a_and_b = counts['a'] + counts['b']
或者使用sum() 来计算一个值在展平序列中出现了多少次:
from itertools import chain
amount_a_and_b = sum(1 for v in chain.from_iterable(l) if v in {'a', 'b'})
在我的 Macbook Pro (OS X 10.11) 上,这两种方法在 Python 3.5.1 上的速度相当:
>>> from timeit import timeit
>>> from collections import Counter
>>> from itertools import chain
>>> l = [(1, 'a', 'b'), (2, 'b', 'c'), (3, 'e', 'a')] * 1000 # make it interesting
>>> def counter():
... counts = Counter(chain.from_iterable(l))
... counts['a'] + counts['b']
...
>>> def summing():
... sum(1 for v in chain.from_iterable(l) if v in {'a', 'b'})
...
>>> timeit(counter, number=1000)
0.5640139860006457
>>> timeit(summing, number=1000)
0.6066895100011607
