简体   繁体   English

如何将每个字典值插入到对应键之后的列表中?

[英]How to Insert Each Dictionary Value into a List After the Corresponding Key?

I have a list of elements and I'd like to insert dictionary values into that list after the key element:我有一个元素列表,我想在关键元素之后将字典值插入到该列表中:

listicle = ['a', 'b', 'c', 'd']
some_new_elements = {'b':'x', 'd':'y'}

giving the following:给出以下内容:

['a', 'b', 'x', 'c', 'd', 'y']

What is the Pythonic way to do this? Pythonic 的方法是什么?

Try to use itertools.chain.from_iterable which is like a flatmap :尝试使用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']

The correct way:正确的方法:

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

A simple way to do that without list comprehension:一种无需列表理解的简单方法:

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

Here is a comprehension to do this:这是执行此操作的理解:

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM