Python setdefault不是左值,有什么解决方法吗?

2024-04-20 03:49:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下小程序:

ages=[23,23,43,54,34,22,43,23]

histogram={}
for age in ages:
    if not age in histogram:
        histogram[age]=1
    else:
        histogram[age]+=1

for age,count in sorted(histogram.items()):
    print "Age: %d Number of people: %d"%(age,count)

它在列表中创建了一个简单的柱状图。但是,我发现在直方图散列中的双重查找非常难看。我知道哈希访问基本上是O(1),所以这并不像看上去那么低效,但仍然。。。在

我尝试过各种解决方法,例如尝试使用setdefault,但以下方法不会奏效:

^{pr2}$

我知道我可以使用defaultdict,但是它改变了创建的histogram dict对象的行为,这不是我想要的。在

如果有办法让我把这个问题设为“低优先级”,我会的,因为这显然不是很重要。但我一直在寻找一个聪明和/或优雅的解决方案来解决这个问题。在

所以,问题是:如何通过dict中的键来增加一个整数,或者如果它不存在,就将它设置为1?在


Tags: 方法in程序forageifcountnot
3条回答

你可以预先初始化dict,即

histogram = dict(((a, 0) for a in set(ages)))

对于这个特定的应用程序,您应该使用a ^{}。在

from collections import Counter

ages = [23,23,43,54,34,22,43,23]

histogram = Counter(ages)

for age,count in sorted(histogram.items()):
    print "Age: %d Number of people: %d"%(age,count)

如果您确实需要dict,可以使用dict构造函数将计数器转换回dict。在

^{pr2}$

这是how ^{} does the counting,适合您的示例。在

histogram_get = histogram.get
for age in ages:
    histogram[age] = histogram_get(age, 0) + 1

相关问题 更多 >