finding and replacing elements in a list

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

    This can be easily done by using enumerate function

    code-

    lst=[1,2,3,4,1,6,7,9,10,1,2]
    for index,item in enumerate(lst):
        if item==1:
            lst[index]=10 #Replaces the item '1' in list with '10'
    
    print(lst)
    

提交回复
热议问题