Python - 简化重复的if语句

2024-07-05 09:08:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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是预定义的。 提前谢谢你的帮助。在


Tags: ofthe方法ifnothaspopulationprint
3条回答

使用有序字典的另一种方法(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

您可以将所有对组织到字典中,并循环使用所有元素:

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

您可以使用两个词典:

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)

一种类似的方法是首先确定未发生变化的人群:

^{pr2}$

或者,您可以有一个单一的结构:

^{3}$

相关问题 更多 >