如何连接字典的键和值

2024-06-16 12:43:02 发布

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

Your team is going camping and you are taking a vote to decide what food to pack for dinner.

Everyone gets a vote and the food item that gets at least one more than half of the votes wins. None of the items wins if nothing gets at least one more than half votes. Assume that every person gets only one vote.

The input will contain a list of food items where each occurrence of an item represents one vote. You should print the winning food item as output. If there is no clear winner, print "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)

Tags: ofthe代码forinputiffoodvalue
3条回答

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

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 = {"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,:-)

而不是查看^ {< CD1> }考虑使用^ {CD2>}。这将为您提供键/值对。您可以在生成器表达式中使用它并调用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

在用这种方法解决了^{}之后,您还应该看看它

相关问题 更多 >