-2

This if-elif is simple and straightforward. index is a 1-D array with values of 0-5 only. As you can see from the image, the only correct if-elif is only for index[i]==0 and index[i]==1. For index[i]==5, it was supposed to print f but the result was printed as d. What went wrong?

Current output:

screenshot of output

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")
martineau
  • 119,623
  • 25
  • 170
  • 301
Projia
  • 3
  • 3

2 Answers2

0

I've tried your code and the issue is related to the fact that in each loop you have some confusion between the index and the value.

Here, using enumerate, I can access both index and value at every loop:

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...")  
Pitto
  • 8,229
  • 3
  • 42
  • 51
0

You can just shorten your code by avoiding those if elifs using a dictionary to map to required values:

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                                                         

EDIT:

To get count of each of the item in the output:

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))
Austin
  • 25,759
  • 4
  • 25
  • 48