我有一个看起来像这样的列表:
[["0"], ["1", "2"], ["4"]]
并且我想获得所有可能的非零长度排列,从这个列表中的每个列表中取出不超过一个元素,甚至只是排列数。所以上面列表的结果将是:
[["0"], ["1"], ["2"], ["4"], ["0", "1"], ["0", "2"], ["1", "4"], ["2", "4"], ["0", "4"], ["0", "1", "4"], ["0", "2", "4"]]
子列表中的元素都是字符串。
我尝试使用 itertools.products 但它只返回使用所有子列表的结果。
>>> import itertools
>>> l = [["0"], ["1", "2"], ["4"]]
>>> list(itertools.product(*l))
[('0', '1', '4'), ('0', '2', '4')]
您提到的工具组合将起作用:
>>> from itertools import product, combinations
>>> l = [["0"], ["1", "2", "4"], ["8", "9"]]
>>> for lngth in range(1, len(l)+1):
... for c in combinations(l, lngth):
... for p in product(*c):
... print(p)
('0',)
('1',)
('2',)
('4',)
('8',)
('9',)
('0', '1')
('0', '2')
('0', '4')
('0', '8')
('0', '9')
('1', '8')
('1', '9')
('2', '8')
('2', '9')
('4', '8')
('4', '9')
('0', '1', '8')
('0', '1', '9')
('0', '2', '8')
('0', '2', '9')
('0', '4', '8')
('0', '4', '9')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句