首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python itertools

Python itertools
EN

Stack Overflow用户
提问于 2019-02-22 17:58:38
回答 4查看 310关注 0票数 1

我有4个列表,有不同数量的元素。我想输出3个单独的列表元素的所有可能的组合。一种方法是使用itertool.combinations (),但使用.combinations时,我只能组合列表中的项。

列表:

代码语言:javascript
复制
colors      = ["blue", "yellow", "green", "black", "magenta"]
numbers     = [1,2,3,4,5,6,7,8]
material = ["beton", "wood", "stone"]
names      = ["Susi", "Klara", "Claire", "Moni"]

结果应该是:

代码语言:javascript
复制
[blue, 1, beton], [blue, 1, Susi], [blue, 2, beton]…
EN

回答 4

Stack Overflow用户

发布于 2019-02-22 18:08:08

您可以使用函数product()

代码语言:javascript
复制
from itertools import product

list(product(colors, numbers, material + names))
票数 3
EN

Stack Overflow用户

发布于 2019-02-22 18:06:01

使用productchain名称和材质:

代码语言:javascript
复制
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))

输出的一部分:

代码语言:javascript
复制
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')
票数 1
EN

Stack Overflow用户

发布于 2019-02-22 18:22:27

组合不同列表中的项需要的是itertools.product,从一组四个列表中选择3个列表需要的是itertools.combinations

下面我提供了这两个工具应用的一个简化的简短示例:

代码语言:javascript
复制
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]:                                                                                  
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54824491

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档