2014-05-09 259 views
6

我很新的蟒蛇,並尋找一種方式,以簡化下面的簡化重複。 在此先感謝您的幫助。Python的if語句

+0

您好!小點;在if語句結束時不要忘記你的冒號。好東西很快被內化。 – FarmerGedden

回答

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

+0

實際上,擁有3元組列表可以避免'not_changed'中的字符查找,即'not_changed =(name for name,initial,total if initial == total)'。 –

+0

@rodrigo你可以請我看看我的例子上面。 – user3619552

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