finding and replacing elements in a list

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

    List comprehension works well, and looping through with enumerate can save you some memory (b/c the operation's essentially being done in place).

    There's also functional programming. See usage of map:

    >>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1]
    >>> map(lambda x: x if x != 4 else 'sss', a)
    [1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]
    

提交回复
热议问题