finding and replacing elements in a list

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

    The following is a very straightforward method in Python 3.x

     a = [1,2,3,4,5,1,2,3,4,5,1]        #Replacing every 1 with 10
     for i in range(len(a)):
       if a[i] == 1:
         a[i] = 10  
     print(a)
    

    This method works. Comments are welcome. Hope it helps :)

    Also try understanding how outis's and damzam's solutions work. List compressions and lambda function are useful tools.

提交回复
热议问题