ls1 = [['b', (1, 1)], ['b', (1, 2)], ['b', (1, 3)], ['c', (2, 1)], ['c', (2, 2)]]
ls2 = ['A', 'B']
from itertools import groupby
key = lambda x: x[1][0]
lens = [len(list(g)) for k, g in groupby(sorted(ls1, key=key), key=key)]
dct = dict(zip(ls2, lens))
我的输出是
{'A': 3, 'B': 2}
如果我使用
,而不是在代码的最后一行使用dictd2 = defaultdict(list)
然后如何在d2中获得相同的输出
答案 0 :(得分:1)
我认为使用defaultdict不会给你带来太多好处,但是这里有一个使用collections.Counter的版本:
ls1 = [['b', (1, 1)], ['b', (1, 2)], ['b', (1, 3)], ['c', (2, 1)], ['c', (2, 2)]]
ls2 = ['A', 'B']
from collections import Counter
lens = Counter(x[1][0] for x in ls1)
d2 = dict((k, v[1]) for k, v in zip(ls2, sorted(lens.items())))
最后一行的略短但可能更令人困惑的替代方案:
d2 = dict(zip(ls2, zip(*sorted(lens.items()))[1]))