我想使用数据集打印一条消息,告诉用户动物杂交村民最常见的性格类型。但是,“懒惰”和“正常”字典键都是最常见的,并且具有相同的值。我不知道如何在不进行硬编码的情况下使它们单独打印。
下面是我的代码:
totalfreq2 = {}
for p_type in personality:
if p_type in totalfreq2:
totalfreq2[p_type] +=1
else:
totalfreq2[p_type] = 1
print(totalfreq2)
maxfreq2 = max(totalfreq2.values())
print(maxfreq2)
toplst = ()
for p_type in totalfreq2:
if totalfreq2[p_type] == 63:
ww = p_type
print(ww)
print("The most common personality type for an Animal Crossing Villager is",ww,)
下面是打印输出:
{'Jock': 57, 'Cranky': 57, 'Peppy': 53, 'Big Sister': 26, 'Lazy': 63, 'Normal': 63, 'Snooty': 57, 'Smug': 37}
63
Normal
The most common personality type for an Animal Crossing Villager is Normal
如何在不进行硬编码的情况下将“Lazy”添加到此邮件?
2条答案
按热度按时间gr8qqesn1#
收集所有具有max值的键,然后使用
.join()
将它们打印出来:输出:
另请参见
collections.Counter
,了解计数项目并获取最常见项目的内置方法,例如:xdnvmnnf2#
看起来你的想法是对的......只需将toplist更改为一个空列表,而不是将值赋给变量
ww
,您可以将值附加到列表中,然后在循环完成后打印列表的内容。有相当多的替代品,你可以使用以及。
列表理解。
也可以使用筛选函数