我是 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/