2013-07-17 87 views
-3

好吧,所以这有点复杂。我有一个函数接受通过txt文件创建的两个字典参数,这些参数已经在其他函数中返回。这些国家参数有一个三字母国家代码作为关键字和相应的国家作为价值。奖牌词典中说三个字母代码是关键词,但是一组包含四个整数,分别对应游戏#,金牌,银牌和铜牌。该功能是通过奖牌字典接受三个字母的国家代码循环,并查看该代码是否是奖牌字典中的键。有三种可能性:如果是,那么它应该创建一个格式如下的列表:[ [‘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

请修复您的代码格式。 – Tadeck

+2

为什么不直接修正缩进,而不是对它进行说明?另外,你想让人们阅读你的文字墙吗? – Marcin

+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字典代码映射到数字集。这是行不通的,因为套牌是无序的,所以无法分辨哪些数字是金牌,哪些是银牌,等等。
  • 虽然我认为medalscountries将始终保持相同的代码,我添加了一些检查,以确保。
相关问题