csv 如何分别打印具有相同值的两个字典键?

ecr0jaav  于 2022-12-15  发布在  其他
关注(0)|答案(2)|浏览(124)

我想使用数据集打印一条消息,告诉用户动物杂交村民最常见的性格类型。但是,“懒惰”和“正常”字典键都是最常见的,并且具有相同的值。我不知道如何在不进行硬编码的情况下使它们单独打印。
下面是我的代码:

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”添加到此邮件?

gr8qqesn

gr8qqesn1#

收集所有具有max值的键,然后使用.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]
...
xdnvmnnf

xdnvmnnf2#

看起来你的想法是对的......只需将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)

相关问题