finding and replacing elements in a list

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

    If you have several values to replace, you can also use a dictionary:

    a = [1, 2, 3, 4, 1, 5, 3, 2, 6, 1, 1]
    dic = {1:10, 2:20, 3:'foo'}
    
    print([dic.get(n, n) for n in a])
    
    > [10, 20, 'foo', 4, 10, 5, 'foo', 20, 6, 10, 10]
    

提交回复
热议问题