finding and replacing elements in a list

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

提交回复
热议问题