用另一个列表的内容替换列表项 [英] Replacing list item with contents of another list

查看:95
本文介绍了用另一个列表的内容替换列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于这个问题,但不能代替一个项目与另一个项目,我想用列表的内容替换任何一个项目的出现.

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

很明显,我的意思是替换项目的 all 项,而不仅仅是第一项. (对未在回答中涉及此情况的任何人表示歉意.)

made it clear I meant to replace all occurrences of the item, rather than just the first. (Apologies to anyone who didn't cover that case in their answer.)

推荐答案

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

Different approach: when I'm doing replacements, I prefer to think in terms of dictionaries. So I'd do something like

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

最后一行是标准拼合习惯用法.

where the last line is the standard flattening idiom.

这种方法的一个优点(劣势?)是它将处理'c'的多次出现.

One advantage (disadvantage?) of this approach is that it'll handle multiple occurrences of 'c'.

[更新:]

或者,如果您愿意:

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

关于修改后的测试用例:

On the revised test case:

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

这篇关于用另一个列表的内容替换列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆