Python将+1添加到dict中包含的列表项中

2024-05-14 16:38:47 发布

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

首先,我有一个清单,上面有一些运动员的信息,如下所示:

athletes = [{"name":"Robert", "country":"england", "event": "athletics men's 50000 metres", "medal":"gold"}, 
{"name":"Jan", "country":"england", "event": "athletics men's 50000 metres", "medal":"silver"}....]

我需要根据罗伯特所在国家的名称和他们(在特定项目中的国家)获得的奖牌数量创建一个dict,它应该如下所示:

{'canada': [0, 0, 1], 'china': [1, 0, 0]...}

第一名代表金牌,第二名代表银牌,第三名代表铜牌

{“奖牌”:}可以有“金”、“银”、“铜”或“na”(不适用)

我试过这样做:

def funct(athletes:list, event:str):
    import copy
    list1 = [0, 0, 0]
    dicc = {}
    for i in athletes:
        if i["event"] == event and i["medal"] != 'na':
            dicc[i["country"]] = copy.deepcopy(list1)
        for country in dicc.keys():
            if country == i["country"] and i["medal"] == "gold":
                dicc[country][0] +=1
            elif country == i["country"] and i["medal"] == "silver":
                dicc[country][1] +=1
            elif country == i["country"] and i["medal"] == "bronze":
                dicc[country][2] +=1
return dicc

print(funct(athletes, "athletics men's 50000 metres"))

这是可行的,但我只是得到了该国最后一名运动员的信息(使用上面的列表):

{'england': [0, 1, 0]

我应该得到(预期结果)的时间:

{'england': [1, 1, 0]

我该怎么做才能解决这个问题


Tags: andnameevent信息代表country运动员athletes
1条回答
网友
1楼 · 发布于 2024-05-14 16:38:47

您可以尝试以下操作:

不要在每次迭代后重置国家/地区的计数器:

def funct(athletes:list, event:str):
    import copy
    list1 = [0, 0, 0]
    dicc = {}
    for i in athletes:
        if i["event"] == event and i["medal"] != 'na':
            if i["country"] not in dicc: # only initialize if not existing
                dicc[i["country"]] = copy.deepcopy(list1)
        for country in dicc.keys():
            if country == i["country"] and i["medal"] == "gold":
                dicc[country][0] +=1
            elif country == i["country"] and i["medal"] == "silver":
                dicc[country][1] +=1
            elif country == i["country"] and i["medal"] == "bronze":
                dicc[country][2] +=1
return dicc

print(funct(athletes, "athletics men's 50000 metres"))

相关问题 更多 >

    热门问题