使用列表项作为键并将它们的出现次数作为值创建字典

create dictionary with list items as keys and their number of occurance as value

我有一个这样的列表:

my_list = [1, 1, 1, 1, 1, 2, 2, 2, 3]

我想制作这样的字典:

result = {1: 5, 2: 3, 3: 1}
# key is unique list items
# and value is the times they have been repeated in list

我可以通过这段代码完成这个,但看起来不太好:

def parse_list(my_list):
    result = {}
    my_set = set(my_list)
    for i in my_set:
        result[i] = len([j for j in my_list if j == i])
    return result

我认为这应该可以通过更少的循环来实现。 有什么想法吗?

您可以使用 collections.Counter:

>>> from collections import Counter
>>> my_list = [1, 1, 1, 1, 1, 2, 2, 2, 3]
>>> Counter(my_list)
Counter({1: 5, 2: 3, 3: 1})

>>> dict(Counter(my_list))
{1: 5, 2: 3, 3: 1}