Python - 简化重复的if语句

时间:2014-05-09 08:40:43

标签: 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是预定义的。 提前感谢您的帮助。

3 个答案:

答案 0 :(得分:6)

您可以使用两个词典:

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)

答案 1 :(得分:1)

您可以将所有对组织成字典并循环遍历所有元素:

    populations = { 'a':[10,80], 'b':[10,56], 'c':[90,90] }

    for i in populations:
        if populations[i][1] == populations[i][0]:
            print(i + '\'s population has not changed')

答案 2 :(得分:0)

使用有序字典的另一种方式(2.7):

from collections import OrderedDict

a = OrderedDict((var_name,eval(var_name)) 
              for var_name in sorted(['atotal','ainitial','btotal','binitial']))
while True:
    try:
         init_value = a.popitem(last=False)
         total_value = a.popitem(last=False)
         if init_value[1] == total_value[1]:
             print ("The population of {0} has "
                    "not changed".format(init_value[0][0].upper()))
    except:
         break