finding and replacing elements in a list

前端 未结 16 2456
南方客
南方客 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 06:07

    You can simply use list comprehension in python:

    def replace_element(YOUR_LIST, set_to=NEW_VALUE):
        return [i
                if SOME_CONDITION
                else NEW_VALUE
                for i in YOUR_LIST]
    

    for your case, where you want to replace all occurrences of 1 with 10, the code snippet will be like this:

    def replace_element(YOUR_LIST, set_to=10):
        return [i
                if i != 1  # keeps all elements not equal to one
                else set_to  # replaces 1 with 10
                for i in YOUR_LIST]
    
    0 讨论(0)
  • 2020-11-22 06:08

    I know this is a very old question and there's a myriad of ways to do it. The simpler one I found is using numpy package.

    import numpy
    
    arr = numpy.asarray([1, 6, 1, 9, 8])
    arr[ arr == 8 ] = 0 # change all occurrences of 8 by 0
    print(arr)
    
    0 讨论(0)
  • 2020-11-22 06:10

    List comprehension works well, and looping through with enumerate can save you some memory (b/c the operation's essentially being done in place).

    There's also functional programming. See usage of map:

    >>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1]
    >>> map(lambda x: x if x != 4 else 'sss', a)
    [1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]
    
    0 讨论(0)
  • 2020-11-22 06:10

    This can be easily done by using enumerate function

    code-

    lst=[1,2,3,4,1,6,7,9,10,1,2]
    for index,item in enumerate(lst):
        if item==1:
            lst[index]=10 #Replaces the item '1' in list with '10'
    
    print(lst)
    
    0 讨论(0)
提交回复
热议问题