2

此问题类似,但不是用另一个项目替换一个项目,而是我想用列表的内容替换任何一个项目的出现。

orig = [ 'a', 'b', 'c', 'd', 'c' ]
repl = [ 'x', 'y', 'z' ]
desired = [ 'a', 'b', 'x', 'y', 'z', 'd', 'x', 'y', 'z' ]

# these are all incorrect, or fail to compile
[ repl if x == 'c' else x for x in orig ]
[ [a for a in orig] if x == 'c' else x for x in orig ]
[ (a for a in orig) if x == 'c' else x for x in orig ]
[ a for a in orig if x == 'c' else x for x in orig ]

编辑:明确表示我的意思是替换所有出现的项目,而不仅仅是第一个。(向没有在回答中涵盖该案例的任何人道歉。)

4

5 回答 5

6
>>> 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']

当然,如果您不知道它'c'位于索引 2,您可以使用它orig.index('c')来查找该信息。

于 2013-02-19T16:51:10.270 回答
4

不同的方法:当我做替换时,我更喜欢用字典来思考。所以我会做类似的事情

>>> orig = [ 'a', 'b', 'c', 'd' ]
>>> rep = {'c': ['x', 'y', 'z']}
>>> [i for c in orig for i in rep.get(c, [c])]
['a', 'b', 'x', 'y', 'z', 'd']

最后一行是标准的扁平化习语。

这种方法的一个优点(缺点?)是它可以处理多次出现的'c'.

[更新:]

或者,如果您愿意:

>>> from itertools import chain
>>> list(chain.from_iterable(rep.get(c, [c]) for c in orig))
['a', 'b', 'x', 'y', 'z', 'd']

关于修改后的测试用例:

>>> orig = [ 'a', 'b', 'c', 'd', 'c' ]
>>> rep = {'c': ['x', 'y', 'z']}
>>> list(chain.from_iterable(rep.get(c, [c]) for c in orig))
['a', 'b', 'x', 'y', 'z', 'd', 'x', 'y', 'z']
于 2013-02-19T16:59:43.503 回答
2

不需要任何花哨的东西:

desired = orig[:2] + repl + orig[3:]

要找到2您可以搜索orig.index('c').

x = orig.index('c')
desired = orig[:x] + repl + orig[x+1:]

如果 repl 不是列表,只需使用list(repl)

于 2013-02-19T16:52:52.850 回答
0

如果您向后枚举,您可以随时扩展列表,因为您移动的项目已经通过了枚举。

>>> 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']
于 2013-02-19T17:23:26.743 回答
0

还有一种方式:

>>> import operator
>>> orig = [ 'a', 'b', 'c', 'd', 'c' ]
>>> repl = [ 'x', 'y', 'z' ]
>>> output = [repl if x == 'c' else [x] for x in orig]
>>> reduce(operator.add, output)
['a', 'b', 'x', 'y', 'z', 'd', 'x', 'y', 'z']
>>> 
于 2013-02-19T18:25:32.053 回答