简体   繁体   English

如何在非唯一项列表中使用字典理解

[英]How to Use a Dictionary Comprehension on a List of Non-Unique Items

Yesterday, I was working on a problem where I wanted to take a list of non-unique items and make a dictionary out of them that had unique versions of the items in the list mapped to the number of times each appeared. 昨天,我正在研究一个问题,我想要列出一些非独特的项目,并从中创建一个字典,列表中的项目的唯一版本映射到每个项目出现的次数。 This sounds pretty straight forward, and I immediately started writing a dictionary comprehension for it, only to realize once I started that I had no idea how to finish because the keys I'm running through aren't unique, and the values should be additive. 这听起来非常简单,我立即开始为它编写字典理解,只是为了实现一旦我开始我不知道如何完成因为我正在运行的键不是唯一的,并且值应该是加法的。 Still it feels like there ought to be an elegant dictionary comprehension for this. 仍然觉得应该有一个优雅的字典理解。 Ideas? 想法?

What I want is a comprehension that does the following: 我想要的是一种能够完成以下工作的理解:

#given
lst = [1,1,1,7,5,8,3,8,5,9,1]
#do
a_dict = defaultdict(int)
for item in lst:
    a_dict[item] +=1

The Counter class in the collections module looks like it may do what you want. 集合模块中Counter类似乎可以执行您想要的操作。

You can do something like this: 你可以这样做:

from collections import Counter
a_dict = Counter(lst)

Versions of Python older than 2.7 do not have the Counter class, but you may be able to do something like this: 早于2.7的Python版本没有Counter类,但您可以执行以下操作:

a_dict = dict((x, lst.count(x)) for x in set(lst))

The set conversion is not necessary. set转换不是必需的。 It may make the code run faster for large lists with many identical items but I don't know for sure because I haven't benchmarked it. 对于包含许多相同项目的大型列表,它可能会使代码运行得更快,但我不确定,因为我没有对它进行基准测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM