![](/img/trans.png)
[英]How to save key corresponding to every value of a dictionary in a list in Python?
[英]How to Insert Each Dictionary Value into a List After the Corresponding Key?
我有一个元素列表,我想在关键元素之后将字典值插入到该列表中:
listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}
给出以下内容:
['a', 'b', 'x', 'c', 'd', 'y']
Pythonic 的方法是什么?
尝试使用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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.