【问题标题】:two dictionaries, making a list两本词典,列一个清单
【发布时间】:2013-07-16 13:32:12
【问题描述】:

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

【问题讨论】:

  • 请修正您的代码格式。
  • 为什么不只是修复缩进,而不是做一个注释呢?另外,您希望人们阅读您的文字墙吗?
  • 应该也可以修复未闭合的字符串...
  • 帮助他人 - 尝试提供以下内容。假设输入“Britain” - medalList 应该在其末尾包含什么,以及它在 medals 中的相关条目是什么?
  • medalList 是上述假定返回列表的变量名称。最后,它需要具有与该特定国家相关联的奖牌数量,其信息可在先前函数中创建的字典奖牌中找到,如果包含,则 somestrng 应该在该字典中索引在所述字典中

标签: python file list function dictionary


【解决方案1】:

这应该可行:

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 将代码映射到数字集。这是行不通的,因为集合是无序的,因此无法分辨哪个数字是金牌,哪个是银牌等。请改用元组或列表。
  • 虽然我假设 medalscountries 将始终拥有相同的代码,但我添加了一些检查以确保。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-24
    • 2020-05-13
    • 2014-10-16
    • 1970-01-01
    相关资源
    最近更新 更多