gpt4 book ai didi

Python - 简化重复的 if 语句

转载 作者:太空狗 更新时间:2023-10-29 22:30:26 24 4
gpt4 key购买 nike

我是 python 的新手,正在寻找一种方法来简化以下内容:

if atotal == ainitial:
print: "The population of A has not changed"
if btotal == binitial:
print: "The population of B has not changed"
if ctotal == cinitial:
print: "The population of C has not changed"
if dtotal == dinitial:
print: "The population of D has not changed"

显然 _total 和 _initial 是预定义的。在此先感谢您的帮助。

最佳答案

您可以使用两个词典:

totals   = {'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0}
initials = {'A' : 0, 'B' : 0, 'C' : 0, 'D' : 0}
for k in initials:
if initials[k] == totals[k]:
print "The population of {} has not changed".format(k)

类似的方法是先确定未变化的种群:

not_changed = [ k for k in initials if initials[k] == totals[k] ]
for k in not_changed:
print "The population of {} has not changed".format(k)

或者,你可以有一个单一的结构:

info = {'A' : [0, 0], 'B' : [0, 0], 'C' : [0, 0], 'D' : [0, 0]} 
for k, (total, initial) in info.items():
if total == initial:
print "The population of {} has not changed".format(k)

关于Python - 简化重复的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23560168/

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