finding and replacing elements in a list

前端 未结 16 2667
南方客
南方客 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: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]
    >>> 
    

提交回复
热议问题