gpt4 book ai didi

python - 在 Python 中,我可以在一个条件中处理两个变量吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:53:37 28 4
gpt4 key购买 nike

是否可以简化这个?也许结合两者?教我 DRY 的方法 :-\

o = old_last_result
if o == 7:
old_last_result_msg = result_7
elif o == 12:
old_last_result_msg = result_12
elif o == 23:
old_last_result_msg = result_23
elif o == 24:
old_last_result_msg = result_24
elif o == 103:
old_last_result_msg = result_103
elif o == 1000:
old_last_result_msg = result_1000
else:
old_last_result_msg = "Error code: #%s" % old_last_result

n = new_last_result
if n == 7:
new_last_result_msg = result_7
elif n == 12:
new_last_result_msg = result_12
elif n == 23:
new_last_result_msg = result_23
elif n == 24:
new_last_result_msg = result_24
elif n == 103:
new_last_result_msg = result_103
elif n == 1000:
new_last_result_msg = result_1000
else:
new_last_result_msg = "Error code: #%s" % new_last_result

最佳答案

result_msgs = {
7: result_7,
12: result_12,
...
}

old_last_result_msg = result_msgs.get(old_last_result,
"Error code: #%s" % old_last_result)
new_last_result_msg = result_msgs.get(new_last_result,
"Error code: #%s" % new_last_result)

关于python - 在 Python 中,我可以在一个条件中处理两个变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834284/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com