Python工具

2024-06-28 15:08:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有4个不同元素数的列表。我想输出3个单独列表元素项的所有可能组合。 一种方法是itertool.组合(),但使用.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]…

Tags: 方法元素列表greenbluematerialblackcolors
3条回答

使用productchain名称和材料:

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')

您需要组合来自不同列表的项的是itertools.product,您需要从一组四个列表中选择三个列表的是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]:                                                                                  

您可以使用函数product()

from itertools import product

list(product(colors, numbers, material + names))

相关问题 更多 >