【问题标题】:Print specific Permutations of a list in Python在 Python 中打印列表的特定排列
【发布时间】:2020-09-27 16:12:47
【问题描述】:

对于列表的所有排列,我只想打印特定索引处的值大于先前索引处的值的那些排列。这样的索引将被称为“大索引” 例如:如果列表是[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 中的排列库来生成排列。一个简单易懂的解决方案将不胜感激。

【问题讨论】:

  • 一个“大索引”是一个大于它的索引的值?
  • “大索引”是指其元素大于前面索引处的元素的索引。
  • 所以一个伟大的索引是一个“迄今为止更大”的价值?第一个元素总是被认为是伟大的?
  • 是的,绝对的。
  • 欢迎您!你有没有尝试过任何事情来实现这一目标?你能和我们分享一下吗?您在使代码正常工作时是否遇到了具体问题?我们希望帮助您成为更好的程序员,而不仅仅是为您工作。这个论坛的目的不是为人们编写代码,而是帮助讨论具体的编码问题,帮助提问者和后来的人更好地理解所涉及的语言和工具。

标签: python permutation


【解决方案1】:

这应该可行:

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

【讨论】:

  • 我懂一点,不擅长Python one liner。您能否解释一下逻辑或添加 cmets 以便我知道它是如何工作的?感谢您的意见。
  • 我加了一些cmets,希望对你有帮助
  • 非常感谢! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
相关资源
最近更新 更多