简体   繁体   English

Python:如何获取列表集的所有有序组合

[英]Python: how to get all the ordered combinations of set of lists

let say I have the following lists: 假设我有以下列表:

a = [1, 2, 3]
b = [11, 12, 13]
c = [111, 112, 113]

I want to have the following output 我想要以下输出

[1,2,3]
[1,2,13]
[1,2,113]
[1,12,3]
[1, 12, 13]
[1, 12, 113]
[1,112,3]
[1,112,13]
[1, 112, 113]
[11,2,3]
[11, 2, 13]
[11, 2, 113]
[11, 12, 3]
[11, 12, 13]
[11, 12, 113]
[11, 112, 3]
[11, 112, 13]
[11, 112, 113]
...

Hence, I want to have a function that will give me all the listing combinations, which are selections of some members of a set where order is disregarded - a set of lists when each element in them keep his index from the original list. 因此,我希望有一个函数可以为我提供所有列表组合,这是对不考虑顺序的集合中某些成员的选择-一组列表,其中每个元素中的每个元素都保持其原始列表的索引不变。

I went over all the options in itertools and didn't find any solution. 我遍历了itertools所有选项,但没有找到任何解决方案。

Just zip your lists before using product : 使用product前,只需zip列表:

from itertools import product

a = [1, 2, 3]
b = [11, 12, 13]
c = [111, 112, 113]

for p in product(*(zip(a, b, c))):
    print(p)

Output: 输出:

(1, 2, 3)
(1, 2, 13)
(1, 2, 113)
(1, 12, 3)
(1, 12, 13)
(1, 12, 113)
(1, 112, 3)
(1, 112, 13)
(1, 112, 113)
(11, 2, 3)
(11, 2, 13)
(11, 2, 113)
(11, 12, 3)
....

To answer your comment: the output of zip is: 回答您的评论: zip的输出为:

print(list(zip(a, b, c)))
#  [(1, 11, 111), (2, 12, 112), (3, 13, 113)]

Then product will generate its output by taking one value in each of these 3 tuples. 然后product将通过在这三个元组中每个取一个值来生成其输出。

 a = [1, 2, 3]
 b = [11, 12, 13]
 c = [111, 112, 113]
 d=[]
 for i in range(3):
     d.append((a[i],b[i],c[i]))
 print(d)
 for i in range(len(d)):
     for k in range(3):
         for j in range(3):
             print(d[0][i],d[1][k],d[2][j])

This will help i guess 这将有助于我猜

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM