finding and replacing elements in a list

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

    Try using a list comprehension and the ternary operator.

    >>> a=[1,2,3,1,3,2,1,1]
    >>> [4 if x==1 else x for x in a]
    [4, 2, 3, 4, 3, 2, 4, 4]
    

提交回复
热议问题