Changing values in list: Python

前端 未结 3 2129
庸人自扰
庸人自扰 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:19

    When you iterate through the loop, you are iterating the loop elements and not the indexes. You need to use enumerate to get the indexes along with the values.

    A small demo can be

    def modifyValues(l):
        for i,x in enumerate(l):   # Use enumerate here. 
            if x == 1:
                l[i] = 'a'
            elif x == 2:
                l[i] = 'b'
            elif x == 3:
                l[i] = 'c'
        print (l)
    

    Output

    ['a', 'b', 'c', 'b', 'c', 'a', 'b', 'b']
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-18 14:46

    You should dictionary instead to change item in the list.

    >>> def modifyValues(l):
    ...     d = {'a': 1, 'b': 2, 'c': 3}
    ...     modifyl = [k for i in l for k in d  if d[k] == i]
    ...     print(modifyl)
    ... 
    >>> modifyValues([1, 2, 3, 2, 3, 1, 2, 2])
    ['a', 'b', 'c', 'b', 'c', 'a', 'b', 'b']
    >>>
    

    You can also use the ascii_lowercase constant from string

    >>> from string import ascii_lowercase
    >>> def modifyValues(l):
    ...     modifyl = [v for i in l for k, v in enumerate(ascii_lowercase, 1)  if i == k]
    ...     print(modifyl)
    ... 
    >>> modifyValues([1, 2, 3, 2, 3, 1, 2, 2])
    ['a', 'b', 'c', 'b', 'c', 'a', 'b', 'b']
    
    0 讨论(0)
提交回复
热议问题