如何连接字典的键和值



你的团队要去露营,你要投票决定晚餐要打包什么食物。

每个人都有投票权,至少获得过半数选票的食品获胜。如果没有任何项目获得至少超过一半的选票,则没有一个项目获胜。假设每个人只有一票。

输入将包含一个食物项目列表,其中每出现一个项目代表一票。您应该将获胜的食物项目打印为输出。如果没有明确的获胜者,请打印"NOTA"。

Input1: {'a','b','a','a','b','b'}
output1: NOTA
Input2: {'a','b','a','a','b','b','b'}
output2: b

我已经写了代码,它给了我重复值的计数。

import ast,sys
input_str = sys.stdin.read()
votes = ast.literal_eval(input_str)
d = {}
for i in votes:
if i not in d:
d[i]=1
else:
d[i] = d[i]+1

上面的代码给了我所有重复值的计数,例如对于Input1,它返回dict_values[3,3]

但我想在字典中将键和值连接在一起。例如:{'a': 3, 'b':3},这样我就可以使用下面的代码。

vals = list(d.values())    
for value in vals:
if value[0]==value[1]:
print('NOTA')
else:
if value[0] > value[1]:
print(max(d.key()) (something like this)

我结合了这两个函数,并稍微修复了代码:

import ast,sys
input_str = sys.stdin.readline()
votes = ast.literal_eval(input_str)
num_of_votes = len(votes)
d = {}
for i in votes:
if i not in d:
d[i]=1
else:
d[i] = d[i]+1
vals = d
winner=False
for value in vals:
if vals[value]>num_of_votes//2:
print(value)
winner=True
break
if not winner:
print("NOTA")

与其查看d.values(),不如考虑使用d.items()。这将为您提供键/值对。您可以在生成器表达式中使用它,并调用next()来获取键的值。当没有任何要返回的内容时,next()采用默认值。例如:

def winner(votes):
d = {}
for i in votes:
if i not in d:
d[i]=1
else:
d[i] = d[i]+1
# get the key for a value that's greater than half
# or NOTA if there isn't one
return next((k for k, v in d.items() if v > len(votes)//2), 'NOTA')
winner(['a','b','a','a','b','b', 'b'])
# 'b'
winner(['a','b','a','a','b','b'])
# NOTA

您还应该在以这种方式解决collections.Counter之后查看它。

字典已经具备了您需要的格式。所以我想这样做

d = {"a": 3, "b": 5}
if len(set(d.values())) == 1: # check whether all the values are euqal.
print("NOTA")
else:
print(max(d, key=d.get))

这应该做你需要的,最好的部分,你可以有不仅仅是a,b,你可以拥有c,和d,:-(

您可以计数d中的键数,其值等于最大值,并且只有当计数为1:时才输出获胜者

max_votes = max(d.values())
winners = [name for name, votes in d.items() where votes == max_votes]
if len(winners) == 1:
print(winner[0])
else:
print('NOTA')

您可以计算重复值的出现次数,如下所示:

d2 = {}
Input2 = ['a','b','a','a','b','b','b']
# Input 2 
for character in Input2:
d2[character] = d2.get(character, 0) + 1
# Out[2]: {'a': 3, 'b': 4}

只需使用max()即可获得获胜者:例如:输入2的获胜者是:

**在Input2 的情况下,max(d2)max(d2, key=d2.get)->'b'->'b'是赢家

import ast,sys
input_str = sys.stdin.read()
votes = ast.literal_eval(input_str)
my_dict = {}
# Loop to count occurenec of food items
for i in set(votes):
my_dict[i] = votes.count(i)
# Finding out max votes
max_votes = max(my_dict.values())
# Checking if max votes > half the votes
if max_votes > len(my_dict)//2:
# Checking if there is no conflicting max votes
if list(my_dict.values()).count(max_votes) < 2:
print(list(my_dict.keys())[list(my_dict.values()).index(max_votes)])
else:
print('NOTA')
# Default value
else:
print('NOTA')

最新更新