finding and replacing elements in a list

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

提交回复
热议问题