简体   繁体   English

Python中两个列表中两个dict的笛卡尔积

[英]Cartesian product of two dict in two lists in Python

Here is my code.这是我的代码。

>>> a = [{'a': 1}, {'b': 2}]
>>> b = [{'c': 3}, {'d': 4}]

I want to show:我想展示:

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

Is there a way I can do it only with list/dict comprehension?有没有办法只能通过列表/字典理解来做到这一点?

A one line, no import solution can consist of a lambda function:一行,没有导入解决方案可以包含一个lambda函数:

f = lambda d, c:[c] if not d else [i for k in d[0] for i in f(d[1:], {**c, **k})]

a = [{'a': 1}, {'b': 2}]
b = [{'c': 3}, {'d': 4}]
print(f([a, b], {}))

Output:输出:

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

However, a much cleaner solution can include itertools.product :但是,更itertools.product解决方案可以包括itertools.product

from itertools import product
result = [{**j, **k} for j, k in product(a, b)]

Output:输出:

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

You can try this.你可以试试这个。

a = [{'a': 1}, {'b': 2}]
b = [{'c': 3}, {'d': 4}]
d = [ {**i, **j} for i in a for j in b ]
print(d) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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