在 Python 中打印列表的特定排列

Print specific Permutations of a list in Python

对于列表的所有排列,我只想打印特定索引处的值大于先前索引处的值的那些排列。这样的索引将被称为“伟大的索引” 例如:如果列表是 [1,2,3],它的排列是

(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

我只想打印只有 n 个“大指数”的排列。假设 n=2,则输出为:

[1,3,2],[2,1,3] and [2,3,1]

[1,3,2] 中,索引 0 和 1 是很好的索引,因为 1(在索引 0 处)没有任何先前元素,而 3(在索引 1 处)大于其先前元素,即 1。 2(在索引 2) 不是“大索引”,因为它不大于其前一个元素 3。 相似地, 在 [2,1,3] 中,索引 0 和 2 是很好的索引。 在 [2,3,1] 中,索引 0 和 1 是很好的索引。 我正在使用 Python 中的排列库来生成排列。一个简单易懂的解决方案将不胜感激。

这应该有效:

import itertools
def great(l, n): #function that counts the permutations of list l with n great indices
    def count_of_great(k): #function that counts the great indices of list k
        c=1 #because first element is always great
        for i in range(1,len(k)):
            if k[i]>max(k[:i]): #if the value is greater than all previous values we increase c
                c+=1
        return c #this is the count of great indices in k
    return [p for p in itertools.permutations(l) if count_of_great(p)==n] #this is a list of permutations of l that have a count_of_great eual with n

great([1,2,3], 2)

输出:

[(1, 3, 2), (2, 1, 3), (2, 3, 1)]