Python - 简化重复的if语句

6

我是一个刚接触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是预定义的。 非常感谢您的帮助。

你好!一个小细节;不要忘记在 if 语句的末尾加上冒号。这是一个需要快速内化的好习惯。 - FarmerGedden
3个回答

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)

2
我更喜欢使用键值对字典。或者如果数据更加复杂,可以使用自定义类和该类对象的字典。 - rodrigo
@FrerichRaabe 在我上面的例子中,这会是什么样子? - user3619552
@rodrigo k 是什么? - user3619552
1
@user3619552:k 是字典的键,也就是字母。(total, initial) 是一对值。 - rodrigo
@rodrigo 这是我目前的代码,但是没有任何反应? - user3619552
显示剩余4条评论

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')

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接