finding and replacing elements in a list

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

    On long lists and rare occurrences its about 3x faster using list.index() - compared to single step iteration methods presented in the other answers.

    def list_replace(lst, old=1, new=10):
        """replace list elements (inplace)"""
        i = -1
        try:
            while 1:
                i = lst.index(old, i + 1)
                lst[i] = new
        except ValueError:
            pass
    

提交回复
热议问题