【问题标题】:Try and Except Implementation Questions尝试并排除实施问题
【发布时间】:2018-02-18 06:06:54
【问题描述】:

我收到了一份文件,其中包含国家/地区及其所在大洲的列表。分配的说明是使用 try 和 except 函数来生成带有大陆键的字典,每个大陆对应的国家将是值。我设法使用 for 循环来解决这个问题,但我不知道如何使用 try 和 except 函数。我试过这样做,但是在测试程序时收到很多错误消息。我想知道应该如何实现 try 和 except 函数来解决作业中的问题。

提供给我们的列表输出国家信息如下:

print(countries[0])

这里,安道尔已经被选中,输出为:

{'timezones': ['Europe/Andorra'], 'code': 'AD', 'continent': 'Europe', 
'name': 'Andorra', 'capital': 'Andorra la Vella'}

我的代码:

from countries import countries
from pprint import pprint


continent_countries = {}
i=0

for country in countries:
#try:  
    continent_inputter = {country['continent']:[]}
    continent_countries.update(continent_inputter)
#except KeyError:
# print("TESTING. NONE. TRY AGAIN. ")

for country in countries:
    if 'Europe' == country['continent']:
        continent_countries['Europe'].append(country['name'])

    elif 'Oceania' == country['continent']:
        continent_countries['Oceania'].append(country['name'])

    elif 'Africa' == country['continent']:
        continent_countries['Africa'].append(country['name'])

    elif 'North America' == country['continent']:
        continent_countries['North America'].append(country['name'])

    elif 'South America' == country['continent']:
         continent_countries['South America'].append(country['name'])

    elif 'Asia' == country['continent']:
          continent_countries['Asia'].append(country['name'])
    i+=1

print(continent_countries)

【问题讨论】:

  • Try/Except 子句用于说明通常会停止/中断程序的异常情况。您当然不能将循环换成 try 块并期望具有相同的功能。考虑阅读本文并使用您认为正确的内容进行编辑:docs.python.org/3/tutorial/errors.html
  • 我收到了很多错误信息是一个绝对没有意义的问题描述,除非你包含这些错误信息。如果您在理解作业时遇到困难,请向您的导师寻求帮助。他们把它给了你,并且确切地知道到目前为止你的课程所涵盖的内容,并且他们会得到报酬来回答你的问题。
  • 你怎么又发这个问题了?

标签: python python-3.x python-2.7 python-requests try-catch


【解决方案1】:
for country in countries:
    continent = country['continent']
    if continent_countries.get(continent) is None:
        continent_countries[continent] = [country['name']]
    else:
        continent_countries[continent].append(country['name'])

【讨论】:

    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 2017-03-01
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多