📜  Python - K 连续最大值

📅  最后修改于: 2022-05-13 01:54:21.134000             🧑  作者: Mango

Python - K 连续最大值

给定一个列表,从每个索引中找到最多下 K 个元素。

方法 #1:使用循环 + max() + 切片

在此,我们迭代循环中的元素,切片直到下一个 K,并使用 max() 来获取当前索引的最大值。

Python3
# Python3 code to demonstrate working of 
# K consecutive Maximum 
# Using max() + loop + slicing
  
# initializing list
test_list = [4, 3, 8, 2, 6, 7, 4, 3, 2, 4, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 4
  
res = []
for idx in range(len(test_list) - K + 1):
      
    # slice next K and compute Maximum
    res.append(max(test_list[idx : idx + K]))
  
# printing result 
print("Next K Maximum List : " + str(res))


Python3
# Python3 code to demonstrate working of 
# K consecutive Maximum 
# Using list comprehension
  
# initializing list
test_list = [4, 3, 8, 2, 6, 7, 4, 3, 2, 4, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 4
  
# one-liner to solve problem
res = [max(test_list[idx : idx + K]) for idx in range(len(test_list) - K + 1)]
  
# printing result 
print("Next K Maximum List : " + str(res))


输出
The original list is : [4, 3, 8, 2, 6, 7, 4, 3, 2, 4, 5]
Next K Maximum List : [8, 8, 8, 7, 7, 7, 4, 5]

方法#2:使用列表推导

这是解决这个问题的另一种方法,使用列表理解的上述方法的单行替代方案。

Python3

# Python3 code to demonstrate working of 
# K consecutive Maximum 
# Using list comprehension
  
# initializing list
test_list = [4, 3, 8, 2, 6, 7, 4, 3, 2, 4, 5]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 4
  
# one-liner to solve problem
res = [max(test_list[idx : idx + K]) for idx in range(len(test_list) - K + 1)]
  
# printing result 
print("Next K Maximum List : " + str(res))
输出
The original list is : [4, 3, 8, 2, 6, 7, 4, 3, 2, 4, 5]
Next K Maximum List : [8, 8, 8, 7, 7, 7, 4, 5]