如何在python中对所有排列的列表进行混洗?

时间:2018-06-26 07:26:25

标签: python list shuffle

我有以下列表列表:

columns1 = ["title", "abstract","groups"]
columns2 = ["title", "abstract","groups","keywords"]
columns3 = ["title", "abstract","groups","topics"]
columns4 = ["title", "abstract","groups","keywords","topics"]
columns5 = ["title", "abstract","groups","topics","keywords"]
columns6 = ["title", "abstract","keywords"]
columns7 = ["title", "abstract","keywords","groups"]
columns8 = ["title", "abstract","keywords","topics"]
columns9 = ["title", "abstract","keywords","groups","topics"]
columns10 = ["title", "abstract","keywords","topics","groups"]
columns11 = ["title", "abstract","topics"]
columns12 = ["title", "abstract","topics","groups"]
columns13 = ["title", "abstract","topics","keywords"]
columns14 = ["title", "abstract","topics","groups","keywords"]
columns15 = ["title", "abstract","topics","keywords","groups"]

如您所见,我想将前两个词保持原样,并针对所有不同的排列(或组合-我忘记了哪个)对接下来的三个词进行混洗。

如何创建带有循环的列表?

1 个答案:

答案 0 :(得分:2)

这确实是排列而不是组合,因为您想考虑[a,b,c][a,c,b]的不同

为此,您可以创建一个像这样的循环:

elements_base = ["title", "abstract"]
elements_plus = ["groups","topics","keywords"]

import itertools
for i in range(3):
    for element in itertools.permutations(elements_plus,i+1):
        print(elements_base + list(element))

结果是:

['title', 'abstract', 'groups']
['title', 'abstract', 'topics']
['title', 'abstract', 'keywords']
['title', 'abstract', 'groups', 'topics']
['title', 'abstract', 'groups', 'keywords']
['title', 'abstract', 'topics', 'groups']
['title', 'abstract', 'topics', 'keywords']
['title', 'abstract', 'keywords', 'groups']
['title', 'abstract', 'keywords', 'topics']
['title', 'abstract', 'groups', 'topics', 'keywords']
['title', 'abstract', 'groups', 'keywords', 'topics']
['title', 'abstract', 'topics', 'groups', 'keywords']
['title', 'abstract', 'topics', 'keywords', 'groups']
['title', 'abstract', 'keywords', 'groups', 'topics']
['title', 'abstract', 'keywords', 'topics', 'groups']