计算列表中第二个元素的频率? (Python)

问题描述:

我希望能够输出第二位数字发生的次数。例如:计算列表中第二个元素的频率? (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)