Python – 用列表展平字典
给定一个列表和字典,用列表中键的可用元素位置处的键和值来展平字典。
Input : test_list = [“Gfg”, “is”, “Best”, “For”, “Geeks”], subs_dict = {“Gfg” : 7}
Output : [‘Gfg’, 7, ‘is’, ‘Best’, ‘For’, ‘Geeks’]
Explanation : “Gfg” is replaced, followed by its value in dictionary.
Input : test_list = [“Gfg”, “is”, “Best”, “For”, “Geeks”], subs_dict = {“gfg” : 7, “best” : 8}
Output : [‘Gfg’, ‘is’, ‘Best’, ‘For’, ‘Geeks’]
Explanation : No replacement. No matching values.
方法 #1:使用列表理解 + get()
上述功能的组合可以用来解决这个问题。在此,我们使用 get() 附加所有键是否存在检查,以及列表中的值。
Python3
# Python3 code to demonstrate working of
# Flatten Dictionary with List
# Using get() + list comprehension
# initializing list
test_list = ["Gfg", "is", "Best", "For", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {"Gfg" : 7, "Geeks" : 8}
# get() to perform presence checks and assign value
temp = object()
res = [ele for sub in ((ele, subs_dict.get(ele, temp))
for ele in test_list) for ele in sub if ele != temp]
# printing result
print("The list after substitution : " + str(res))
Python3
# Python3 code to demonstrate working of
# Flatten Dictionary with List
# Using chain.from_iterable() + list comprehension
from itertools import chain
# initializing list
test_list = ["Gfg", "is", "Best", "For", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {"Gfg" : 7, "Geeks" : 8}
temp = ([ele, subs_dict[ele]] if ele in subs_dict
else [ele] for ele in test_list)
# chain.from_iterable() for flattening
res = list(chain.from_iterable(temp))
# printing result
print("The list after substitution : " + str(res))
输出
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks']
The list after substitution : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks', 8]
方法 #2:使用 chain.from_iterable() + 列表推导
这是可以执行此任务的另一种方式。在此,我们形成键值对列表,如果存在则追加,如果不存在则保留元素。接下来,使用 chain.from_iterable() 执行键值列表的扁平化。
Python3
# Python3 code to demonstrate working of
# Flatten Dictionary with List
# Using chain.from_iterable() + list comprehension
from itertools import chain
# initializing list
test_list = ["Gfg", "is", "Best", "For", "Geeks"]
# printing original list
print("The original list : " + str(test_list))
# initializing subs. Dictionary
subs_dict = {"Gfg" : 7, "Geeks" : 8}
temp = ([ele, subs_dict[ele]] if ele in subs_dict
else [ele] for ele in test_list)
# chain.from_iterable() for flattening
res = list(chain.from_iterable(temp))
# printing result
print("The list after substitution : " + str(res))
输出
The original list : ['Gfg', 'is', 'Best', 'For', 'Geeks']
The list after substitution : ['Gfg', 7, 'is', 'Best', 'For', 'Geeks', 8]