【问题标题】:Simple if elif mismatched result [duplicate]如果 elif 不匹配的结果很简单 [重复]
【发布时间】:2018-05-05 13:03:45
【问题描述】:

这个if-elif 简单明了。 index 是一个一维数组,其值仅为0-5。从图中可以看出,唯一正确的if-elif 仅适用于index[i]==0index[i]==1。对于index[i]==5,它应该打印f,但结果打印为d。出了什么问题?

当前输出:

for i in index:
    print(i)
    if index[i]==0:
      print(" :a")
    elif index[i]==1:
        print(" :b")
    elif index[i]==2:
        print(" :c")
    elif index[i]==3:
        print(" :d")
    elif index[i]==4:
        print(" :e")
    elif index[i]==5:
        print(" :f")

【问题讨论】:

  • 索引值是多少?
  • 是类型吗?如果是整数类型,则为整数
  • 我的意思是,什么是价值,你已经分配给 for 循环中的索引?
  • i 循环遍历 ,而不是 index 的索引!你只需要i 而不是index[i]
  • @AndrasDeak 哦,我明白了!谢谢!这解决了问题

标签: python arrays for-loop if-statement


【解决方案1】:

您可以通过避免使用字典来映射到所需值的ifelifs 来缩短代码:

index = [1, 5, 5, 5, 5, 4, 4, 4, 0]
map_dict = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f"}

for i in index:
    print(map_dict.get(i))

# b
# f                                                        
# f                                                      
# f                                                        
# f                                                         
# e                                                  
# e                                                      
# e                                                       
# a                                                         

编辑

获取输出中每个项目的计数:

from collections import Counter

index = [1, 5, 5, 5, 5, 4, 4, 4, 0]
map_dict = {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f"}

lst = []
for i in index:
    value = map_dict.get(i)
    print(value)
    lst.append(value)

print(Counter(lst))

【讨论】:

  • 是否可以计算输出的每个'a','b','c','d','e'和'f'的总数?因为在 if elif 中,我可以使用 countera+=1 等
  • @Projia collections.Counter(index) 获取每个索引的计数,然后使用上面的dict获取字符数。
  • 立即查看编辑。
  • 感谢@AndrasDeak 和theausome。字典似乎非常方便和直接。将了解更多信息。
【解决方案2】:

我已经尝试过您的代码,问题与在每个循环中您在索引和值之间存在一些混淆的事实有关。

在这里,使用枚举,我可以在每个循环中访问索引和值:

index_list = [10,4,2,3,4,15,7]

for index, value in enumerate(index_list):
    print "\nCurrent index: " + str(index)
    print "Current value: " + str(value)
    print "Current result:"
    if value==0:
        print(" :a")
    elif value==1:
        print(" :b")
    elif value==2:
        print(" :c")
    elif value==3:
        print(" :d")
    elif value==4:
        print(" :e")
    elif value==5:
        print(" :f")
    else:
        print("This value is not in the 0 - 5 range, skipping it...")  

【讨论】:

  • 你只是犯了和 OP 一样的错误。试试index = [10,11,12] 等。
  • 确实正确!现在应该可以工作了
  • @AndrasDeak 我想我明白了:D 谢谢 :)
  • 是的。现在只有一个风格备注:如果有的话,请在任何地方使用val :)
  • 完全同意,@AndrasDeak。正如您指出的那样,我现在改进了样式并添加了一些调试打印。我的猪现在也有口红了:D 感谢您的建议和耐心。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 2019-08-07
  • 2018-03-16
相关资源
最近更新 更多