use*_*552 6 python if-statement repeat
我是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"
Run Code Online (Sandbox Code Playgroud)
显然_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)
Run Code Online (Sandbox Code Playgroud)
类似的方法是首先确定未改变的人口:
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)
Run Code Online (Sandbox Code Playgroud)
或者,您可以拥有一个结构:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
237 次 |
| 最近记录: |