好吧,这有点复杂。我有一个函数接受通过txt文件创建的两个字典参数,这些参数已经在其他函数中返回。 countries参数有三个字母的国家/地区代码作为键,相应的国家/地区为值。奖牌词典已经说三个字母代码作为关键,但是包含四个整数的集合分别对应于游戏,金牌,银牌和铜牌。该功能是通过奖牌字典接受三个字母的国家代码循环,并查看代码是否是奖牌字典中的密钥。可能会出现三种可能性:如果是,则应该创建一个如下格式的列表:[
[‘Country’,’Code’,’Gold’,’Silver’,’Bronze’],
[‘Great Britain’
,
‘GRE’
,800, 400, 750]
]
。这部分编译并制作一个列表,但游戏部分需要从奖牌键值中删除,并作为分支列表而不是元组/集合物返回。如果字符串不是字典中的键,那么如果字符串为空,则会将具有上述格式的每个国家/地区添加到列表中。这部分不是编译,因为我认为我在飞行中错误地循环。如果字符串不为空且不在字典中,则返回[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'))
答案 0 :(得分:0)
这应该有效:
def findMedals(countries, medals):
code = raw_input("input a three letter country code and i'll see if I can find it: ")
header = ['Country','Code','Gold','Silver','Bronze']
entry = lambda c: [countries[c], c] + list(medals[c][1:]) # creates one table line
if code == "":
# wildcard -> add each line to table
return [header] + [entry(c) for c in medals if c in countries]
elif code in countries and code in medals:
# valid code -> add one line to table
return [header, entry(code)]
else:
# return 'invalid' line
return [['INVALID CODE', 'n/a']]
countries = {"GER": "Germany", "GBR": "Breat Britain", "USA": "USA", "FOO": "No Medals"}
medals = {"GER": (0,1,2,3), "GBR": (3,4,5,6), "USA": (6,7,8,9)} # tuples, not sets!
res = findMedals(countries, medals)
for line in res:
print "\t".join(map(str, line))
一些指示:
for
循环很奇怪。您正在迭代items()
,即键和值的元组,而不是单独的键in
字典medals
dict将代码映射到数字集。这不起作用,因为套装是无序的,所以没有办法分辨哪个数字是金牌,银牌等等。而是使用tutples或列表。medals
和countries
将始终保持相同的代码,但我添加了一些检查以确保。