Replacing list item with contents of another list

后端 未结 5 1616
日久生厌
日久生厌 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:12

    >>> orig = [ 'a', 'b', 'c', 'd' ]
    >>> repl = [ 'x', 'y', 'z' ]
    >>> desired = list(orig)  #can skip this and just use `orig` if you don't mind modifying it (and it is a list already)
    >>> desired[2:3] = repl
    >>> desired
    ['a', 'b', 'x', 'y', 'z', 'd']
    

    And of course, if you don't know that 'c' is at index 2, you can use orig.index('c') to find out that information.

提交回复
热议问题