【问题标题】:Writing less elif statement少写 elif 语句
【发布时间】:2016-07-21 06:25:35
【问题描述】:

我需要这方面的帮助。

a = ["cat","dog","fish","hamster"]

 user = raw_input("choose your fav pet ")

if user == a[0]:

    print a[0]

elif user == a[1]:

    print a[1]

elif user == a[2]:

    print a[2]

elif user == a[3]:

    print a[3]

else:

    print "sorry, the aninimal you type does not exist"

我想做的是一个测试移动应用,所以我使用动物作为测试。该程序确实有效,但问题是世界上有超过 100 种动物,我将它们放在一个列表中,我不想创建很多 elif 语句。

有没有办法让它更短更快?

【问题讨论】:

标签: python python-2.7 if-statement


【解决方案1】:

使用for 循环:

for animal in a:
    if user == animal:
        print animal
        break
else:
    print "Sorry, the animal you typed does not exist"

不过,我注意到这段代码有点傻。如果您在找到与用户条目匹配的动物时要做的就是打印它,您可以改为检查该条目是否在 a 列表中,如果在 print user 中:

if user in a:
    print user
else:
    print "Sorry, the animal you typed does not exist"

【讨论】:

    【解决方案2】:

    我会选择:

    if user in a:
        print user
    

    这将检查user 输入是否在宠物列表中,如果是,它将打印出来。

    【讨论】:

    • 甚至print(a.get(user, "sorry, the animal you type does not exist"))
    • @csl: a 是一个列表而不是dict,所以没有a.get 方法可以调用。
    【解决方案3】:

    使用 in 运算符:

    if user in a:
        print user
    else : 
        print "sorry, the aninimal you type does not exist"
    

    【讨论】:

      【解决方案4】:
       a = ["cat","dog","pig","cat"]
          animal = input("enter animal:")
      
          if animal in a:
              print (animal , "found")
          else:
              print ("animal you entered not found in the list")
      

      上面的代码很适合你的要求。

      【讨论】:

      • 您的答案是否为现有答案增加了价值(或者您的解决方案与之前的答案有很大不同)?
      【解决方案5】:

      我想添加一种新方法,我无法猜测每个人是如何错过的。我们必须检查不区分大小写的字符串。

      a = ["cat","dog","fish","hamster"]
      
      user = raw_input("choose your fav pet ")
      // adding for user case where user might have entered DOG, but that is valid match
      matching_obj = [data for data in a if data.lower() == user.lower()]
      
      if matching_obj:
          print("Data found ",matching_obj)
      else:
          print("Data not found")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-28
        相关资源
        最近更新 更多