我有一些组数据,例如 a、b、c 等。我想做的是根据数据计算出所有可能的组合。如果输入数据的计数始终相同就可以了。但就我而言,我想假设输入数据的计数是从 0 到 N,我的意思是 a、b、c、d、e ...
我想我必须使用循环。但是我不确定使用循环循环来解决这个问题。
输入
a = ["x", "y"]
b = ["q", "w", "c"]
c = ["i", "o", "p"]
...
输出
预期输出是所有组合与每个值的所有组合。
[{a:[], b:["q"], c:["i", "o"]}, {a:["x"], b:[], c:["o"]}, ...]
请您参考如下方法:
如果我明白你在找什么,你可以使用 itertools.product()在powersets输入(文档中有 powerset() 的配方)。 map()函数可用于将 powerset 应用于每个输入。
from itertools import product, combinations, chain
from pprint import pprint
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
names = ['a', 'b', 'c']
a = ["x", "y"]
b = ["q", "w", "c"]
c = ["i", "o", "p"]
result = []
for values in product(*map(powerset, [a, b, c])):
result.append(dict(zip(names, values)))
pprint(result)
这是它的工作原理:
首先,它构建幂集:
>>> list(powerset(["x", "y"]))
[(), ('x',), ('y',), ('x', 'y')]
>>>
>>> list(powerset(["x", "y"]))
[(), ('x',), ('y',), ('x', 'y')]
>>> list(powerset(["q", "w", "c"]))
[(), ('q',), ('w',), ('c',), ('q', 'w'), ('q', 'c'),
('w', 'c'), ('q', 'w', 'c')]
>>> list(powerset(["i", "o", "p"]))
[(), ('i',), ('o',), ('p',), ('i', 'o'), ('i', 'p'),
('o', 'p'), ('i', 'o', 'p')]
下一页 product()从每个幂集中提取一个元素:
>>> for values in product(*map(powerset, [a, b, c])):
print(values)
((), (), ())
((), (), ('i',))
((), (), ('o',))
((), (), ('p',))
((), (), ('i', 'o'))
((), (), ('i', 'p'))
((), (), ('o', 'p'))
((), (), ('i', 'o', 'p'))
((), ('q',), ())
((), ('q',), ('i',))
((), ('q',), ('o',))
((), ('q',), ('p',))
((), ('q',), ('i', 'o'))
((), ('q',), ('i', 'p'))
((), ('q',), ('o', 'p'))
((), ('q',), ('i', 'o', 'p'))
最后,我们zip()将上述结果与变量 names 一起构成 dict() :
# What zip does
>>> list(zip(['a', 'b', 'c'], ((), ('q',), ('i', 'o', 'p'))))
[('a', ()), ('b', ('q',)), ('c', ('i', 'o', 'p'))]
# What dict does with the zip:
>>> dict(zip(['a', 'b', 'c'], ((), ('q',), ('i', 'o', 'p'))))
{'b': ('q',), 'c': ('i', 'o', 'p'), 'a': ()}
