我有4个列表,有不同数量的元素。我想输出3个单独的列表元素的所有可能的组合。一种方法是使用itertool.combinations (),但使用.combinations时,我只能组合列表中的项。
列表:
colors = ["blue", "yellow", "green", "black", "magenta"]
numbers = [1,2,3,4,5,6,7,8]
material = ["beton", "wood", "stone"]
names = ["Susi", "Klara", "Claire", "Moni"]结果应该是:
[blue, 1, beton], [blue, 1, Susi], [blue, 2, beton]…发布于 2019-02-22 18:08:08
您可以使用函数product()
from itertools import product
list(product(colors, numbers, material + names))发布于 2019-02-22 18:06:01
使用product和chain名称和材质:
from itertools import chain, product
colors = ["blue", "yellow", "green", "black", "magenta"]
numbers = [1,2,3,4,5,6,7,8]
material = ["beton", "wood", "stone"]
names = ["Susi", "Klara", "Claire", "Moni"]
out = product(colors, numbers, chain(material, names))输出的一部分:
for i in range(10):
print(next(out))
('blue', 1, 'beton')
('blue', 1, 'wood')
('blue', 1, 'stone')
('blue', 1, 'Susi')
('blue', 1, 'Klara')
('blue', 1, 'Claire')
('blue', 1, 'Moni')
('blue', 2, 'beton')
('blue', 2, 'wood')
('blue', 2, 'stone')发布于 2019-02-22 18:22:27
组合不同列表中的项需要的是itertools.product,从一组四个列表中选择3个列表需要的是itertools.combinations。
下面我提供了这两个工具应用的一个简化的简短示例:
In [57]: from itertools import product, combinations
In [58]: a, b, c = ['stone','concrete'], ['Jane','Mary'], [1,2,3]
In [59]: for l1, l2 in combinations((a,b,c), 2):
...: for i1, i2 in product(l1,l2):
...: print(i1, i2)
stone Jane
stone Mary
concrete Jane
concrete Mary
stone 1
stone 2
stone 3
concrete 1
concrete 2
concrete 3
Jane 1
Jane 2
Jane 3
Mary 1
Mary 2
Mary 3
In [60]: https://stackoverflow.com/questions/54824491
复制相似问题