如何匹配两个列表并插入特定值?

How to match two lists and insert into specific value?

我有两个列表

a = ['b','c','a','d','v']
g = [{'c':'1'},{'c':'2'},{'c':'3'},{'d':'1'},{'d':'2'}]

我想将列表g中的字典中的键与列表a中的元素进行匹配,如果匹配则将列表g中的元素插入到列表a中。

期望的结果是:

['b','c',{'c':'1'},{'c':'2'},{'c':'3'},'a','d',{'d':'1'},{'d':'2'},'v']

尝试使用 sorted:

print(sorted(a + g, key=lambda x: list(x)[0]))

输出:

['a', 'b', 'c', {'c': '1'}, {'c': '2'}, {'c': '3'}, 'd', {'d': '1'}, {'d': '2'}, 'e']
a = ['a','b','c','d','e']
g = [{'c':'1'},{'c':'2'},{'c':'3'},{'d':'1'},{'d':'2'},{'z':'1'}]

for dic in g:
    for key in dic:
        if key in a:
            a.append(dic)
print(a)

#output ['a', 'b', 'c', 'd', 'e', {'c': '1'}, {'c': '2'}, {'c': '3'}, {'d': '1'}, {'d': '2'}]

在此之后,如果需要,您可以使用 lambda 进行排序。

尝试:

a = ["b", "c", "a", "d", "v"]
g = [{"c": "1"}, {"c": "2"}, {"c": "3"}, {"d": "1"}, {"d": "2"}]

tmp = {}
for d in g:
    for k in d:
        tmp.setdefault(k, []).append(d)

out = []
for v in a:
    out.append(v)
    out.extend(tmp.get(v, []))

print(out)

打印:

['b', 'c', {'c': '1'}, {'c': '2'}, {'c': '3'}, 'a', 'd', {'d': '1'}, {'d': '2'}, 'v']