Changing values in list: Python

前端 未结 3 2137
庸人自扰
庸人自扰 2020-12-18 13:39

I\'m making a function to modify the elements in a list, but it doesn\'t change all the way through... My function is:

def modifyValues(l):
    for x in l:
          


        
3条回答
  •  心在旅途
    2020-12-18 14:27

    Your code is incorrect, because when you iterate your list def modifyValues(l):

    for x in l: // the value of x will be the position of value
            if x == 1:// your if condition does not check for the value in the list, it only checks the position.
                l[x] = 'a'
            elif x == 2:
                l[x] = 'b'
            elif x == 3:
                l[x] = 'c'
        print (l)
    

    To improve your code use this as your if condition

     if l[x] == 1
    

提交回复
热议问题