我想打印一条消息,告诉用户使用数据集的动物穿越村民最常见的性格类型。然而,'Lazy'和'Normal'字典键都是最常见的,并且具有相同的值。我不知道如何使它们分开打印而不硬编码。
下面是我的代码:
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"添加到此消息中?
收集所有具有最大值的键,然后使用.join()
精确地打印它们:
# The missing data matching the OP's output.
personality = ['Jock'] * 57 + ['Cranky'] * 57 + ['Peppy'] * 53 + ['Big Sister'] * 26 + ['Lazy'] * 63 + ['Normal'] * 63 + ['Snooty'] * 57 + ['Smug'] * 37
totalfreq2 = {}
for p_type in personality:
if p_type in totalfreq2:
totalfreq2[p_type] +=1
else:
totalfreq2[p_type] = 1
maxfreq2 = max(totalfreq2.values())
# find all keys with same max value
toplist = [k for k,v in totalfreq2.items() if v == maxfreq2]
print(f"The most common personality type for an Animal Crossing Villager is: {', '.join(toplist)}")
输出:
The most common personality type for an Animal Crossing Villager is: Lazy, Normal
请参见collections.Counter
,以获得一个内置的方法来计数项目,并获得最常见的,例如:
import collections
...
totalfreq2 = collections.Counter(personality)
# Returns counts sorted highest to lowest and gets the first one.
# It returns [(key, count)] hence the subscripting to get the count.
maxfreq2 = totalfreq2.most_common(1)[0][1]
...
看起来你的想法是对的…只需将toplist更改为空列表,而不是将值赋给变量ww
,您可以将值附加到列表中,然后在循环完成后打印列表的内容。
maxfreq2 = max(totalfreq2.values())
toplst = []
for p_type in totalfreq2:
if totalfreq2[p_type] == maxfreq2:
toplst.append(p_type)
print(toplst)
你也可以使用很多其他的选择。
列表理解。
[print(i) for i in totalfreq2 if totalfreq2[i] == maxfreq2]
或者你可以使用过滤器函数
for ptype in filter(lambda x: totalfreq2[x] == maxfreq2, totalfreq2.keys()):
print(ptype)