我希望能夠輸出第二位數字發生的次數。例如:計算列表中第二個元素的頻率? (Python)
L=[['a',1], ['b',2], ['c',2], ['d',5]]
,計數器將返回:
1: 1 time(s)
2: 2 time(s)
5: 1 time(s)
我希望能夠輸出第二位數字發生的次數。例如:計算列表中第二個元素的頻率? (Python)
L=[['a',1], ['b',2], ['c',2], ['d',5]]
,計數器將返回:
1: 1 time(s)
2: 2 time(s)
5: 1 time(s)
collections.Counter
存在正是這樣的工作:
>>> collections.Counter(i[1] for i in L).most_common()
[(2, 2), (1, 1), (5, 1)]
from collections import defaultdict
appearances = defaultdict(int)
for i in L:
appearances[i[1]] += 1
>>> from collections import Counter
>>> L = [['a', 1], ['b', 2], ['c', 2], ['d', 5]]
>>> for n, c in Counter(n for c, n in L).most_common():
print '{0}: {1} time(s)'.format(n, c)
2: 2 time(s)
1: 1 time(s)
5: 1 time(s)