【问题标题】:Python - simplify repeated if statementsPython - 简化重复的 if 语句
【发布时间】:2014-05-09 08:40:42
【问题描述】:

我对 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 语句末尾的冒号。快速内化是件好事。

标签: python if-statement repeat


【解决方案1】:

您可以使用两个字典:

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)

【讨论】:

  • 我更喜欢成对的字典。或者,如果数据更有趣,可以使用自定义类和此类对象的字典。
  • 确实,拥有一个三元组列表可以让您避免在not_changed 中进行字典查找,即not_changed = (name for name, initial, total if initial == total)
  • @rodrigo 你能按照我上面的例子告诉我吗?
  • @FrerichRaabe 根据我上面的例子,这看起来如何?
  • @user3619552:k是字典的key,也就是字母。 (total, ìnitial) 是一对值。
【解决方案2】:

您可以将所有对组织成字典并循环遍历所有元素:

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

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 2015-09-12
      相关资源
      最近更新 更多