【问题标题】:try-except and a list of dictionarytry-except 和字典列表
【发布时间】:2021-08-23 07:26:21
【问题描述】:

我有一个描述格式的字典列表。我想使用 try/except 构造只打印“US”。因为我可能有更多没有“国籍”标签的列表。我只想到 if/else 构造。请帮我。谢谢!

list_components = js['results'][0]['list_components']
    try:
        for item in list_components:
            item["types"] == ["nationality", "political"]
            print('The nationality information for the list:', item["short_name"])
                          
    except:
        print('No nationality is available for this list.')

【问题讨论】:

  • 使用if有什么问题? try 的目的是异常处理,而不是常规的控制流。
  • 没错。我的教授只想使用 try/except。想死我了
  • 条件是只打印“US”(在我假设的 short_name 字段中)还是所有具有国籍的条目?
  • 每个条目的国籍可以更改,有时不会出现。谢谢
  • 如果要使用错误处理机制,则必须触发错误,例如通过尝试访问不存在的字段。然后,您可以捕获特定错误并打印出消息或忽略并继续。如果你想强制它,你可以raise一个错误,当条件不正确但似乎没有意义时。

标签: json python-3.x list dictionary try-except


【解决方案1】:

这是一种非常幼稚的方法来实现您想要实现的目标。但这不是一个好的做法。这就像从某事中创造出某种东西,而忽略了程序员采用的所有良好规则。

list_components = js['results'][0]['list_components'] 

for item in list_components:
    try:
        #Generate error when there is no nationality otherwise print nationality 
        status = item["types"][0] == "nationality"
        status and print("Nationality: ", item["short_name"])
        raise ValueError
    except:
        #Print prompt
        not status and print("No Nationality")

这个解决方案不需要任何 try/catch 结构,可以纯粹用 if-else 来解决。如果其他人需要它,这里有一个更好更简单的解决方案。

for item in list_components:
    print("Nationality: " item["short_name"]) if item["types"][0] == "nationality" else print("No Nationality")

【讨论】:

  • 谢谢!我同意 if 构造,但这是我的教授想要的:(
【解决方案2】:

太大了,无法作为评论发布,所以我将其发布为答案,

此代码适合您吗?我的意思是,try, except 在这里完全没有做任何事情......但是告诉我这是否不是你想要的

list_components = js['results'][0]['list_components']
try:
    for item in list_components:
        item["short_name"] == 'US' and item["types"] == ["nationality", "political"] and print('The nationality information for the list:', item["short_name"])
                      
except:
    print('No nationality is available for this list.')

【讨论】:

  • 您好,感谢您的评论。但是“US”可以根据输入进行更改。不过我会尝试操作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多