简体   繁体   English

我怎样才能漂亮地处理这个肮脏的多次尝试代码

[英]How can I beautifully deal with this dirty-multiple-try code

Hi guys please help me to revise this code.大家好,请帮我修改这段代码。 You probably know what I'm trying to do It isn't critical to have keyError but anyway I want to try every del code.您可能知道我要做什么 有 keyError 并不重要,但无论如何我想尝试每个 del 代码。 It works as I intended, but I'm pretty sure there is more beautiful way to do this.它按我的意图工作,但我很确定有更漂亮的方法来做到这一点。

try:
    del response_json['sha1']
except:
    print("keyError: Fail to delete sha1 hash key")
try:
    del response_json['sha224']
except:
    print("keyError: Fail to delete sha224 hash key")
try:
    del response_json['sha256']
except:
    print("keyError: Fail to delete sha256 hash key")
try:
    del response_json['sha384']
except:
    print("keyError: Fail to delete sha384 hash key")
try:
    del response_json['sha512']
except:
    print("keyError: Fail to delete sha512 hash key")   

I can do this as below but this way if first del code raise error, then the rest of code will not be executed, right?我可以按如下方式执行此操作,但是如果第一个 del 代码引发错误,则不会执行其余代码,对吗?

try:
    del response_json['sha1']
    del response_json['sha224']
    del response_json['sha256']
    del response_json['sha384']
    del response_json['sha512']
except:
    print("keyError: Fail to delete hash key")

Thank you for reading this谢谢您阅读此篇

Use a loop to iterate the values使用循环来迭代值

lst = ['sha1','sha224','sha256','sha384','sha512']
for s in lst:
    try:
        del response_json[s]
    except:
        print(f"keyError: Fail to delete {s} hash key")

I think response_json is a dictionary and not just a list.我认为 response_json 是一本字典,而不仅仅是一个列表。 I think you need something that is more dynamic and adaptable to all situations.我认为你需要一些更具活力和适应所有情况的东西。 Just populate the keys and delete each key-value pair one after the other.只需填充键并一个接一个地删除每个键值对。 This solution goes for any length and any dictionary you might encounter in the future.此解决方案适用于您将来可能遇到的任何长度和任何字典。

json_keys = [ key for key in response_json]
for keys in json_keys:
    try:
        del response_json[keys]
    except:
        print(f"keyError: Fail to delete hash key")      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM