finding and replacing elements in a list

前端 未结 16 2437
南方客
南方客 2020-11-22 05:41

I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this?<

相关标签:
16条回答
  • 2020-11-22 05:45
    a = [1,2,3,4,5,1,2,3,4,5,1,12]
    for i in range (len(a)):
        if a[i]==2:
            a[i]=123
    

    You can use a for and or while loop; however if u know the builtin Enumerate function, then it is recommended to use Enumerate.1

    0 讨论(0)
  • 2020-11-22 05:47
    >>> a=[1,2,3,4,5,1,2,3,4,5,1]
    >>> item_to_replace = 1
    >>> replacement_value = 6
    >>> indices_to_replace = [i for i,x in enumerate(a) if x==item_to_replace]
    >>> indices_to_replace
    [0, 5, 10]
    >>> for i in indices_to_replace:
    ...     a[i] = replacement_value
    ... 
    >>> a
    [6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6]
    >>> 
    
    0 讨论(0)
  • 2020-11-22 05:47

    To replace easily all 1 with 10 in a = [1,2,3,4,5,1,2,3,4,5,1]one could use the following one-line lambda+map combination, and 'Look, Ma, no IFs or FORs!' :

    # This substitutes all '1' with '10' in list 'a' and places result in list 'c':

    c = list(map(lambda b: b.replace("1","10"), a))

    0 讨论(0)
  • 2020-11-22 05:47

    Here's a cool and scalable design pattern that runs in O(n) time ...

    a = [1,2,3,4,5,6,7,6,5,4,3,2,1]
    
    replacements = {
        1: 10,
        2: 20,
        3: 30,
    }
    
    a = [replacements.get(x, x) for x in a]
    
    print(a)
    # Returns [10, 20, 30, 4, 5, 6, 7, 6, 5, 4, 30, 20, 10]
    
    0 讨论(0)
  • 2020-11-22 05:48
    >>> a= [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]
    >>> for n, i in enumerate(a):
    ...   if i == 1:
    ...      a[n] = 10
    ...
    >>> a
    [10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]
    
    0 讨论(0)
  • 2020-11-22 05:53

    Find & replace just one item

    your_list = [1,2,1]     # replace the first 1 with 11
    
    loc = your_list.index(1)
    your_list.remove(1)
    your_list.insert(loc, 11)
    
    0 讨论(0)
提交回复
热议问题