finding and replacing elements in a list

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

    To replace easily all 1 with 10 in a = [1,2,3,4,5,1,2,3,4,5,1]one could use the following one-line lambda+map combination, and 'Look, Ma, no IFs or FORs!' :

    # This substitutes all '1' with '10' in list 'a' and places result in list 'c':

    c = list(map(lambda b: b.replace("1","10"), a))

提交回复
热议问题