finding and replacing elements in a list

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

    Here's a cool and scalable design pattern that runs in O(n) time ...

    a = [1,2,3,4,5,6,7,6,5,4,3,2,1]
    
    replacements = {
        1: 10,
        2: 20,
        3: 30,
    }
    
    a = [replacements.get(x, x) for x in a]
    
    print(a)
    # Returns [10, 20, 30, 4, 5, 6, 7, 6, 5, 4, 30, 20, 10]
    

提交回复
热议问题