2 回答
TA贡献1801条经验 获得超8个赞
您可以使用product从itertools
>>> from itertools import product
>>> a =[[1,2,3],[4,5],[6,7,8,9]]
>>> print ([i for i in product(*a)])
[(1, 4, 6), (1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 6), (1, 5, 7), (1, 5, 8), (1
, 5, 9), (2, 4, 6), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 6), (2, 5, 7), (2, 5
, 8), (2, 5, 9), (3, 4, 6), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 6), (3, 5, 7
), (3, 5, 8), (3, 5, 9)]
>>> print ([sum(i) for i in product(*a)])
[11, 12, 13, 14, 12, 13, 14, 15, 12, 13, 14, 15, 13, 14, 15, 16, 13, 14, 15, 16,
14, 15, 16, 17]
通过采用每个子列表的笛卡尔乘积并对每个子列表求和来进行工作。
当然,可以将其缩短为:
>>> print (list(map(sum, product(*a))))
[11, 12, 13, 14, 12, 13, 14, 15, 12, 13, 14, 15, 13, 14, 15, 16, 13, 14, 15, 16,
14, 15, 16, 17]
使用map无视for循环。
TA贡献1826条经验 获得超6个赞
您可以使用itertools.product
>>> import itertools
>>> s=[[1,2,3],[4,5,6],[7,8,9]]
>>> list(map(sum, itertools.product(*s)))
[12, 13, 14, 13, 14, 15, 14, 15, 16, 13, 14, 15, 14, 15, 16, 15, 16, 17, 14, 15, 16, 15, 16, 17, 16, 17, 18]
添加回答
举报