Python - simplify repeating if statements

I am very new to python and looking for a way to simplify the following:

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" 

Obviously, _total and _initial are predefined. Thanks in advance for any help.

+6
source share
3 answers

You can use two dictionaries:

 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) 

A similar way is to identify unchanged populations:

 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) 

Or you can have one structure:

 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) 
+6
source

You can organize all the pairs in the dictionary and the loop, although all the elements are:

  populations = { 'a':[10,80], 'b':[10,56], 'c':[90,90] } for i in populations: if populations[i][1] == populations[i][0]: print(i + '\ population has not changed') 
+1
source

Another way (2.7) using an ordered dictionary:

 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 
0
source

All Articles