finding and replacing elements in a list

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

    You can simply use list comprehension in python:

    def replace_element(YOUR_LIST, set_to=NEW_VALUE):
        return [i
                if SOME_CONDITION
                else NEW_VALUE
                for i in YOUR_LIST]
    

    for your case, where you want to replace all occurrences of 1 with 10, the code snippet will be like this:

    def replace_element(YOUR_LIST, set_to=10):
        return [i
                if i != 1  # keeps all elements not equal to one
                else set_to  # replaces 1 with 10
                for i in YOUR_LIST]
    

提交回复
热议问题