Python - 根據另一列表中的最大 K 個元素


當需要根據另一個列表獲取 K 個元素的最大值時,使用簡單的迭代、“追加”方法和“最大值”方法。

示例

以下是對它的演示示例 -

my_list_1 = [62, 25, 32, 98, 75, 12, 46, 53]
my_list_2 = [91, 42, 48, 76, 23, 17, 42, 83]

print("The first list is : " )
print(my_list_1)

print("The first list after sorting is : " )
my_list_1.sort()
print(my_list_1)

print("The second list is : " )
print(my_list_2)

print("The first list after sorting is : " )
my_list_2.sort()
print(my_list_2)

K = 42
print("The value of K is ")
print(K)

my_result = []
for index in range(len(my_list_1)):

   if my_list_2[index] == K :
      my_result.append(my_list_1[index])

my_result = max(my_result)

print("The result is : ")
print(my_result)

輸出

The first list is :
[62, 25, 32, 98, 75, 12, 46, 53]
The first list after sorting is :
[12, 25, 32, 46, 53, 62, 75, 98]
The second list is :
[91, 42, 48, 76, 23, 17, 42, 83]
The first list after sorting is :
[17, 23, 42, 42, 48, 76, 83, 91]
The value of K is
42
The result is :
46

說明

  • 定義了兩個列表,並顯示在控制檯上。

  • 使用“排序”方法對其進行排序,並顯示在控制檯上。

  • 定義了 K 的值,並顯示在控制檯上。

  • 定義了一個空列表。

  • 對第一個列表進行迭代。

  • 將第二個列表中特定索引的元素分配給值 K。

  • 將第一個列表中索引中的此元素追加到空列表。

  • 考慮此列表中元素的最大值。

  • 將此元素分配給一個變數。

  • 在控制檯上以輸出的形式顯示它。

更新於: 2021 年 9 月 13 日

116 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.