Search code examples
pythonif-statementfor-in-loop

How to iterate a list with string elements and append a specific value to another list if a specific conditional statement in the first list is true?


I am working in Google Colab. I have a list named dir with string elements. I want to create a new list in which i will append a specific number depending on whether a specific character sequence is found in the elements of the dir list.

Here is the code i wrote:

labels=[]

for value in dir:
  if '/River/' in dir:
    labels.append(1)
  elif '/HerbaceousVegetation/' in dir:
    labels.append(2)
  elif '/Highway/' in dir:
    labels.append(3)
  elif '/Residential/' in dir:
    labels.append(4)
  elif '/Industrial/' in dir:
    labels.append(5)
  elif '/AnnualCrop/' in dir:
    labels.append(6)
  elif '/Pasture/' in dir:
    labels.append(7)
  elif '/PermanentCrop/' in dir:
    labels.append(8)
  elif '/SeaLake/' in dir:
    labels.append(9)
  else:
    labels.append(10)

The result is the list labels which has the value 10 in each element. It seems that the conditional statement takes into account only the else statement. How can i transform my code to take into account all the statements?


Solution

  • The problem here is that you are checking is string in list dir not in the element of list dir. Change the if statements to (el)if 'your_string' in value: and it will work as you expect.