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

ここで、最後の行は標準の平坦化イディオムです。

このアプローチの利点(欠点?)の1つは、の複数の発生を処理できることです'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 に答える