4

我有一个接受字典作为参数的函数(从另一个有效的函数返回)。这个函数应该要求一个字符串作为输入,并查看字典中的每个元素,看看它是否在那里。字典基本上是三个字母的缩写:国家即:AFG:阿富汗等等。如果我要输入“sta”作为我的字符串,它应该将任何具有该切片的国家(如美国、阿富汗、哥斯达黎加等)附加到初始化的空列表中,然后返回所述列表。否则,它返回 [NOT FOUND]。返回的列表应如下所示:[ ['Code','Country'], ['USA','United States'],['CRI','Costa Rica'],['AFG','Afganistan']]等等这是我的代码到目前为止的样子:

def findCode(countries):
    some_strng = input("Give me a country to search for using a three letter acronym: ")
    reference =['Code','Country']
    code_country= [reference]
    for key in countries:
        if some_strng in countries:
            code_country.append([key,countries[key]])
    if not(some_strng in countries):
        code_country.append( ['NOT FOUND'])
    print (code_country)
    return code_country

我的代码只是不断返回 ['NOT FOUND']

4

1 回答 1

5

你的代码:

for key in countries:
    if some_strng in countries:
        code_country.append([key,countries[key]])

应该:

for key,value in countries.iteritems():
    if some_strng in value:
        code_country.append([key,countries[key]])

您需要检查字符串的每个值,假设您的国家/地区在值中而不是键中。

还有您的最终退货声明:

if not(some_strng in countries):
    code_country.append( ['NOT FOUND'])

应该是这样的,有很多方法可以检查:

if len(code_country) == 1
  code_country.append( ['NOT FOUND'])
于 2013-07-17T18:20:25.780 回答