python - 在 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 中的排列库来生成排列。一个简单,易于理解的解决方案将不胜感激。
解决方案
这应该有效:
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)]
推荐阅读
- r - Ryacas 在 Windows 中构建失败
- sql-server - 如何检查 Azure SQL Server 中是否启用了即时文件初始化
- javascript - 如何在mongodb v3.6中排序
- python - Python - 如何修复“ValueError:没有足够的值来解包(预期 2,得到 1)”
- javascript - 同一个地方有多个标记
- python-3.x - 使用 panda 将整列中的时间转换为从 csv 导入的浮点数
- powerbi - Power BI 中的百分比计算
- javascript - Vue.js variable turns undefined
- javascript - Javascript数组显示不是数组错误
- android - 位于imageview Android下方中心的Textview