3

假设我们有一个映射 K -> V,其中域 K 是一个集合([1,2,3]),而共同域 V 是从集合(['a', 'b' ,'C'])。是否有一种简洁的方法可以将所有可能的映射枚举为可迭代(理想情况下是字典列表或生成器):

例如。

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

请注意,域的大小不是固定的,因此这种解决方案并不理想:

[ { 1 : x, 2 : y,  3 : z } for x in V for y in V for z in V ]

干杯

4

2 回答 2

6

使用repeat参数itertools.product

K = set([1, 2, 3])
V = set(['a', 'b', 'c'])
itertools.product(V, repeat=len(K))

然后,您可以dict在理解中构造 s:

(dict(zip(K, x)) for x in itertools.product(V, repeat=len(K)))

检查:

>>> len([dict(zip([1, 2, 3], x)) for x in itertools.product('abc', repeat=3)])
27
于 2012-08-17T16:05:12.623 回答
3

使用itertools.product

import itertools
K,V = [1,2,3], 'abc'
[dict(zip(K, p)) for p in itertools.product(V, repeat=len(V))]
于 2012-08-17T16:04:36.920 回答