如何获取两个列表之间的所有映射? [英] How to get all mappings between two lists?
本文介绍了如何获取两个列表之间的所有映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们有两个列表,A和B:
We have two lists, A and B:
A = ['a','b','c']
B = [1, 2]
在A和B之间包含2 ^ n(此处为2 ^ 3 = 8)的所有映射的集合中,是否存在pythonic方法?那就是:
Is there a pythonic way to build the set of all maps between A and B containing 2^n (here 2^3=8)? That is:
[(a,1), (b,1), (c,1)]
[(a,1), (b,1), (c,2)]
[(a,1), (b,2), (c,1)]
[(a,1), (b,2), (c,2)]
[(a,2), (b,1), (c,1)]
[(a,2), (b,1), (c,2)]
[(a,2), (b,2), (c,1)]
[(a,2), (b,2), (c,2)]
使用itertools.product
,可以获取所有元组:
Using itertools.product
, it's possible to get all the tuples:
import itertools as it
P = it.product(A, B)
[p for p in P]
哪个给:
Out[3]: [('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)]
推荐答案
您可以使用 itertools.product
和 zip
You can do this with itertools.product
and zip
from itertools import product
print [zip(A, item) for item in product(B, repeat=len(A))]
输出
[[('a', 1), ('b', 1), ('c', 1)],
[('a', 1), ('b', 1), ('c', 2)],
[('a', 1), ('b', 2), ('c', 1)],
[('a', 1), ('b', 2), ('c', 2)],
[('a', 2), ('b', 1), ('c', 1)],
[('a', 2), ('b', 1), ('c', 2)],
[('a', 2), ('b', 2), ('c', 1)],
[('a', 2), ('b', 2), ('c', 2)]]
product(B, repeat=len(A))
产生
[(1, 1, 1),
(1, 1, 2),
(1, 2, 1),
(1, 2, 2),
(2, 1, 1),
(2, 1, 2),
(2, 2, 1),
(2, 2, 2)]
然后,我们从产品中选择每个元素,并用A
压缩,以获得所需的输出.
Then we pick each element from the product and zip it with A
, to get your desired output.
这篇关于如何获取两个列表之间的所有映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文