首页 > 解决方案 > 在 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。类似地, In [2,1,3],索引 0 和 2 是大索引。在[2,3,1]中,索引 0 和 1 是很好的索引。我正在使用 Python 中的排列库来生成排列。一个简单,易于理解的解决方案将不胜感激。

标签: pythonpermutation

解决方案


这应该有效:

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)]

推荐阅读