不同大小的笛卡尔积
我可以通过 itertools.product()
函数来获取列表的笛卡尔积:
lists = [['A', 'B'], ['1', '2'], ['x', 'y']]
combinations = itertools.product(*lists)
# [('A', '1', 'x'), ('A', '2', 'y'), ..., ('B', '2', 'y')]
我想要的也是这个,但希望能处理不同大小的组合:
all_comb = magicfunction(lists)
# [('A', '1', 'x'), ..., ('B', '2', 'y'), ('A', '1'), ('A', '2'), ... ('2', 'y'), ... ('y')]
我找不到一个明显的方法来做到这一点。
我需要一种方法,可以让我设置元组的最小和最大大小(我处理的是很长的列表,只需要从7到3的组合,列表的数量和大小会有所不同)。
我的列表更像是:
lists = [['A', 'B', 'C'], ['1', '2'], ['x', 'y', 'z', 'u'], ...] # size may go to a few dozens
2 个回答
2
只需把几个产品串联在一起,按照较小尺寸的组合来进行:
from itertools import chain, product, combinations
def ranged_product(*lists, **start_stop):
start, stop = start_stop.get('start', len(lists)), start_stop.get('stop', 0)
return chain.from_iterable(product(*comb)
for size in xrange(start, stop - 1, -1)
for comb in combinations(lists, r=size))
演示:
>>> lists = [['A', 'B'], ['1', '2'], ['x', 'y']]
>>> for prod in ranged_product(stop=2, *lists):
... print prod
...
('A', '1', 'x')
('A', '1', 'y')
('A', '2', 'x')
('A', '2', 'y')
('B', '1', 'x')
('B', '1', 'y')
('B', '2', 'x')
('B', '2', 'y')
('A', '1')
('A', '2')
('B', '1')
('B', '2')
('A', 'x')
('A', 'y')
('B', 'x')
('B', 'y')
('1', 'x')
('1', 'y')
('2', 'x')
('2', 'y')
4
在编程中,我们常常需要处理一些数据,比如从一个地方获取数据,然后把它放到另一个地方。这个过程就像是把水从一个杯子倒到另一个杯子一样。
有时候,我们可能会遇到一些错误,比如说数据没有正确地传递,或者格式不对。这就像是你想把水从一个杯子倒到另一个杯子,但中间的管子堵了,水就流不过去。
为了避免这些问题,我们可以使用一些工具和方法来检查数据是否正确,确保它能够顺利地从一个地方流到另一个地方。
总之,处理数据就像是管理水流,我们需要确保每一步都顺畅,这样才能得到我们想要的结果。
>>> from itertools import product, combinations
>>> lists = [['A', 'B'], ['1', '2'], ['x', 'y']]
>>> for i in xrange(2, len(lists)+1):
for c in combinations(lists, i):
print list(product(*c))
...
[('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]
[('A', 'x'), ('A', 'y'), ('B', 'x'), ('B', 'y')]
[('1', 'x'), ('1', 'y'), ('2', 'x'), ('2', 'y')]
[('A', '1', 'x'), ('A', '1', 'y'), ('A', '2', 'x'), ('A', '2', 'y'), ('B', '1', 'x'), ('B', '1', 'y'), ('B', '2', 'x'), ('B', '2', 'y')]