使用字典中的信息生成列表

91 阅读3分钟

需要编写一个函数,该函数接收两个字典参数,这两个字典是通过其他函数从文本文件中返回的。两个字典是国家字典和奖牌字典。国家字典的键是三个字母的国家代码,值是对应的国家名称。奖牌字典的键也是三个字母的国家代码,值是一个集合,用以分别表示参加比赛次数、获得的金牌数、银牌数和铜牌数。

huake_00183_.jpg 任务是接受一个包含三个字母的国家代码的字符串,遍历奖牌字典,查看此代码是否在奖牌字典中是键。可能会出现三种情况:1、如果代码是奖牌字典中的键,则函数应创建一个列表,该列表的格式如下:

[[‘Country’,’Code’,’Gold’,’Silver’,’Bronze’],
[‘Great Britain’,‘GRE’,800, 400, 750]
]

这段代码已经可以编译并构建一个列表,但需要从包含奖牌的键值中删除比赛次数,并将比赛次数作为分支列表而不是元组或集合返回。2、如果该字符串不是字典中的键,且字符串为空,则将列表中所有国家信息(以上述格式)添加到列表中。这一部分没有编译,因为即时 for 循环使用了错误的方式。3、如果字符串不为空且不包含在字典中,则返回 ['INVALID CODE', 'n/a']。这一部分可以正确工作。

以下是提供的代码:

def findMedals(countries, medals):
    some_strng = input("input a three letter country code and i'll see if I can find it: ")
    reference  = ['Country','Code','Gold','Silver','Bronze']
    medalList= [reference]
    for key in medals.items():
        if some_strng in key:
            medalList.append([countries[some_strng],key,medals[some_strng]])
            break
        if not some_strng in key:
            if some_strng == '':
                medalList.append([countries[some_string], key for key in countries,medals[some_strng] for key in medals])
            else:
                medalList.append(['INVALID CODE', 'n/a'])
    print(medalList)    
    return(medalList)
    findMedals(country('CountryCodes.txt'),medals('GoldMedals.txt'))

2、解决方案 接下来对代码进行修改,解决遇到的问题:

def findMedals(countries, medals):
    reference  = ['Country','Code','Gold','Silver','Bronze']
    medalList= [reference]
    some_strng = input("input a three letter country code and i'll see if I can find it: ").upper()
    if some_strng in countries:
        medalList.append([countries[some_strng],some_strng,list(medals[some_strng])[1:]])
    elif some_strng == '':
        for key, value in countries.items():
            medalList.append([value, key, list(medals[key])[1:]])
    else:
        medalList.append(['INVALID CODE', 'n/a'])
    print(medalList) 
    return medalList
findMedals(country('CountryCodes.txt'),medals('GoldMedals.txt'))

在修改后的代码中,首先将用户输入的字符串转换为大写形式,以确保与字典中的键进行比较时不会出现大小写敏感的问题。然后,使用 if-elif-else 语句来处理不同的情况:

1、如果用户输入的字符串在国家字典中,则从国家字典中获取国家名称,从奖牌字典中获取奖牌信息(除了比赛次数),并将它们添加到列表中。

2、如果用户输入的字符串为空字符串,则遍历国家字典和奖牌字典,将所有国家信息添加到列表中。

3、如果用户输入的字符串既不在国家字典中也不是空字符串,则将 ['INVALID CODE', 'n/a'] 添加到列表中。

最后,打印列表并返回列表。