有没有办法列出关于计算列表中不同元素的不同变量的出现次数?

时间:2018-05-16 09:25:33

标签: python python-3.x list dictionary counter

sumlist = [
    ['a01', '01-24-2017', 's1'],
    ['a03', '01-24-2017', 's2'],
    ['a03', '09-24-2017', 's1'],
    ['a03', '10-23-2017', 's1'],
    ['a04', '11-01-2017', 's1'],
    ['a04', '11-02-2017', 's2'],
    ['a04', '11-03-2017', 's1'],
    ['a04', '01-01-2017', 's1']]

这是我目前正在处理的列表列表,问题是计算每个元素(a01,a03,a04)的s1和s2的出现次数。我知道的唯一方法是使用count(),但它只适用于单个元素。

我使用Counter和默认值后(感谢@JPP的帮助!):

d = defaultdict(Counter) for animal, date, station in sumlist: d[animal][station] += 1

我明白了:

defaultdict(<class 'collections.Counter'>, {'a04': Counter({'s2': 5, 's1': 5}), 'a01': Counter({'s1': 2, 's2': 1}), 'a03': Counter({'s1': 6, 's2': 4})}

有发生的次数,但有没有办法制作两个字典,如:

{a01: number of occurrences of S1, a04: the number of occureneces of S1, a03: number of occurrences of S1}和S2一样吗?

非常感谢!

2 个答案:

答案 0 :(得分:3)

您要找的是defaultdictCounter个对象:

from collections import defaultdict, Counter

d = defaultdict(Counter)

for key, _, val in sumlist:
    d[key][val] += 1

print(d)

defaultdict(collections.Counter,
            {'a01': Counter({'s1': 1}),
             'a03': Counter({'s1': 2, 's2': 1}),
             'a04': Counter({'s1': 3, 's2': 1})})

如果您希望自己的价值成为关键,请转换keyval

d = defaultdict(Counter)

for key, _, val in sumlist:
    d[val][key] += 1

print(d)

defaultdict(collections.Counter,
            {'s1': Counter({'a01': 1, 'a03': 2, 'a04': 3}),
             's2': Counter({'a03': 1, 'a04': 1})})

答案 1 :(得分:0)

你可以试试这个。

{a:Counter(c[2] for c in l if c[0]==a) for a in set(map(itemgetter(0),l))}

即,

>>> from collections import Counter
>>> from operator import itemgetter
>>> set(map(itemgetter(0),l)) #get the zeroth element to get the keys
set(['a03', 'a01', 'a04'])
>>> {a:0 for a in set(map(itemgetter(0),l))} #dict comprehension
{'a03': 0, 'a01': 0, 'a04': 0}
>>> {a:[c[2] for c in l if c[0]==a] for a in set(map(itemgetter(0),l))} #if the key matches then get the 2nd index
{'a03': ['s2', 's1', 's1'], 'a01': ['s1'], 'a04': ['s1', 's2', 's1', 's1']}
>>> {a:Counter(c[2] for c in l if c[0]==a) for a in set(map(itemgetter(0),l))}
{'a03': Counter({'s1': 2, 's2': 1}), 'a01': Counter({'s1': 1}), 'a04': Counter({'s1': 3, 's2': 1})}