我有一个元素列表,我想把字典值插入到该列表中的键元素之后。
listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}
结果如下
['a', 'b', 'x', 'c', 'd', 'y']
有什么方法可以做到这一点?
尝试使用 itertools.chain.from_iterable
这就像 flatmap
:
from itertools import chain
listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}
output = list(chain.from_iterable([[x, some_new_elements[x]] if x in some_new_elements else [x] for x in listicle]))
print(output) # output: ['a', 'b', 'x', 'c', 'd', 'y']
正确的方法。
import itertools
listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}
new_map = ([m, some_new_elements[m]] if m in some_new_elements else [m] for m in listicle)
print(list(itertools.chain.from_iterable(new_map)))
>>> ['a', 'b', 'x', 'c', 'd', 'y']
一个简单的方法可以做到这一点,而不需要理解清单。
listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}
output = []
for x in listicle:
output.append(x)
if(x in some_new_elements):
output.append(some_new_elements[x])
print(output)
>>>['a', 'b', 'x', 'c', 'd', 'y']
这是一个理解性的方法。
>>> listicle = ['a', 'b', 'c', 'd']
>>> some_new_elements = {'b':'x', 'd':'y'}
>>> sentinel=object()
>>> [x for t in ((e, some_new_elements.get(e, sentinel)) for e in listicle) for x in t if x !=sentinel]
['a', 'b', 'x', 'c', 'd', 'y']