Python - 简化重复的 if 语句

标签 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"

显然 _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/

相关文章:

python - 无法在python中获取页面源代码

python - 如何使用 pyqt 在场景中输出颜色图?

Python enum.Enum 创建别名而不是新值

Java,无限循环 - 仅限 2 的倍数

java - 在3中找到最大的数字,我在最后一部分遇到了粗体字的问题

Swift 2.0 条件赋值和语法

c# - 棘手的正则表达式

python - 如何将 NumPy 数组与 ctypes 一起使用?

c++ - 如何在 CString::Format 中重复一个字符

Java 带条件的重复字符正则表达式