计算列表列表中字符串的出现次数

Count occurrence of strings in list of lists

我想计算一个字符串在另一个列表中的列表中出现的次数,并将其存储在字典列表中,其中每个字典都有一个列表的计数。 例如,

list = [['Sam','John','Alex','Sam','Alex'],['Max','Sam','Max']...]

我希望我的词典列表如下:

count_list = [{'Sam':2,'Alex':2,'John':1}, {'Max':2, 'Sam':1}..] 

我正在遍历每个列表以计算每个字符串出现的次数并将每个结果添加到字典中。但我每次都得到不同的结果,而不是正确的值。

count_list = []
for l in list :
    d = {}
    for str in l:
        if str not in d:
            d[str] = l.count(str)
            count_list.append(d)

任何帮助都是 useful.Thanks。

这里用collections.Counter()会更方便:

>>> from collections import Counter
>>> lst = [["Sam", "John", "Alex", "Sam", "Alex"], ["Max", "Sam", "Max"]]
>>> list(map(Counter, lst))
[Counter({'Sam': 2, 'Alex': 2, 'John': 1}), Counter({'Max': 2, 'Sam': 1})]

如果这样更容易理解,您也可以使用列表理解而不是使用 map()

>>> [Counter(l) for l in lst]
[Counter({'Sam': 2, 'Alex': 2, 'John': 1}), Counter({'Max': 2, 'Sam': 1})]

注意: Counterdict 的子类,因此您可以像普通词典一样对待它们。

如果您愿意,也可以随时转换为 dict()

>>> [dict(Counter(l)) for l in lst]
[{'Sam': 2, 'John': 1, 'Alex': 2}, {'Max': 2, 'Sam': 1}]

您也不应该使用 list 作为变量名,因为它隐藏了内置函数 list()

目前,您正在执行以下操作:

count_list = []
for l in list :
    d = {}
    for str in l:
        if str not in d:
            d[str] = l.count(str)
            count_list.append(d)

请注意,您要为子列表中的每个字符串附加字典,而不是为每个子列表附加一个字典。

执行以下操作应该可以解决问题:

count_list = []
for l in list :
    d = {}
    for str in l:
        if str not in d:
            d[str] = l.count(str)
    count_list.append(d)