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

时间:2012-03-31 02:53:08

标签: python list

我希望能够输出第二个位置数字出现的次数。例如:

L=[['a',1], ['b',2], ['c',2], ['d',5]] 

计数器将返回:

1: 1 time(s)
2: 2 time(s)
5: 1 time(s)

3 个答案:

答案 0 :(得分:3)

对于这种工作,

collections.Counter存在:

>>> collections.Counter(i[1] for i in L).most_common()
[(2, 2), (1, 1), (5, 1)]

答案 1 :(得分:0)

from collections import defaultdict

appearances = defaultdict(int)

for i in L:
    appearances[i[1]] += 1

答案 2 :(得分:0)

>>> 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)