Replacing list item with contents of another list

后端 未结 5 1625
日久生厌
日久生厌 2020-12-21 16:25

Similar to this question, but instead of replacing one item with another, I\'d like to replace any occurrences of one item with the contents of a list.

orig          


        
5条回答
  •  清歌不尽
    2020-12-21 17:13

    If you enumerate backwards, you can extend the list as you go because the items you move have already gone through the enumeration.

    >>> orig = [ 'a', 'b', 'c', 'd', 'c' ]
    >>> repl = [ 'x', 'y', 'z' ]
    >>> desired = [ 'a', 'b', 'x', 'y', 'z', 'd', 'x', 'y', 'z' ]
    >>> for i in xrange(len(orig)-1, -1, -1):
    ...     if orig[i] == 'c':
    ...             orig[i:i+1] = repl
    ... 
    >>> orig
    ['a', 'b', 'x', 'y', 'z', 'd', 'x', 'y', 'z']
    

提交回复
热议问题