gpt4 book ai didi

python - Itertools.按严格顺序排列列表 python

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:57 25 4
gpt4 key购买 nike

假设我有三个列表:

list_1 = ['hello1', 'world1', 'foo1']
list_2 = ['hello2', 'world2', 'foo2']
list_3 = ['hello3', 'world3', 'foo3']

是否可以通过例如 itertools.combinations() 或 itertools.permutations 来实现仅返回以下组合:

combs = ['hello1', 'world1', 'foo1'], ['hello1', 'world2', foo1'], ...
['hello1', 'world1', foo2'], ... ['hello3', 'world2', foo2'], ...

换句话说,我想确保排列遵循每个原始列表中存在的顺序。我确信一定有一个简单的方法,但我似乎找不到它。

提前致谢!

最佳答案

您可以使用itertools.product():

>>> import itertools as it
>>> list(it.product(*zip(list_1, list_2, list_3)))
[('hello1', 'world1', 'foo1'),
('hello1', 'world1', 'foo2'),
('hello1', 'world1', 'foo3'),
('hello1', 'world2', 'foo1'),
...
('hello3', 'world3', 'foo1'),
('hello3', 'world3', 'foo2'),
('hello3', 'world3', 'foo3')]

关于python - Itertools.按严格顺序排列列表 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38164214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com