2014-05-09 12 views
6

Jestem bardzo nowy python i szuka sposobu, aby uprościć następujące:Python - ułatwiają powtarzane if

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" 

Oczywiście _Total i _initial są predefiniowane. Z góry dziękuję za pomoc.

+0

Witam! Niewielki punkt; nie zapomnij swoich dwukropków na końcu instrukcji "if". Dobrze się szybko zinternalizować. – FarmerGedden

Odpowiedz

6

Można korzystać z dwóch słowników:

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) 

podobny sposób po raz pierwszy nie określając zmieniły populacjach:

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) 

Lub można mieć pojedynczą strukturę:

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

Wolałbym słownik par. Lub, jeśli dane są bardziej interesujące, klasa niestandardowa i słownik takich obiektów. – rodrigo

+0

Rzeczywiście, posiadanie listy 3-krotnej pozwoli ci uniknąć unikalnych wyszukiwań w 'not_changed', tj.' Not_changed = (nazwa dla nazwy, początkowa, całkowita, jeśli początkowa == całkowita) '. –

+0

@rodrigo Czy mógłbyś mi pokazać w warunkach mojego przykładu powyżej. – user3619552

1

Możesz uporządkować wszystkie pary w słowniku i cyklować wszystkie elementy:

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

Innym sposobem (2.7) za pomocą uporządkowanej słownika:

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