📜  Python – List 中的每个 Kth 索引最大值

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

Python – List 中的每个 Kth 索引最大值

我们通常希望对列表中的所有元素使用特定的函数。但有时,根据要求,我们希望对列表的某些元素使用特定的功能,基本上是对列表中的每个第 K 个元素。让我们讨论可以执行最大这些元素的某些方式。

方法 #1:使用列表理解 + enumerate() + max()
获取每个第 K 个列表的功能可以在列表理解的帮助下完成,枚举函数有助于整个列表的迭代。 max() 有助于找到最大值。

# Python3 code to demonstrate
# Every Kth index Maximum in List
# using list comprehension + enumerate() + max()
  
# initializing list 
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
  
# printing the original list
print ("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
# using list comprehension + enumerate() + max()
# Every Kth index Maximum in List
# max of every 3rd element
res = max([i for j, i in enumerate(test_list) if j % K == 0 ])
  
# printing result
print ("The max of every kth element : " + str(res))
输出 :
The original list is : [1, 4, 5, 6, 7, 8, 9, 12]
The max of every kth element : 9

方法#2:使用列表理解+列表切片
上述功能可以帮助执行这些任务。列表推导式完成列表中的迭代任务,列表切片完成每个 Kth 元素的提取。

# Python3 code to demonstrate
# The max() helps to find max.
# using list comprehension + list slicing + max()
  
# initializing list 
test_list = [1, 4, 5, 6, 7, 8, 9, 12]
  
# printing the original list
print ("The original list is : " + str(test_list))
  
# using list comprehension + list slicing + max()
# Edit every Kth element in list 
# max of every 3rd element
res = max(test_list[0::3])
  
# printing result
print ("The max of every kth element : " + str(res))
输出 :
The original list is : [1, 4, 5, 6, 7, 8, 9, 12]
The max of every kth element : 9