使用 Python 在元組中找出最大和最小 K 元素


當需要在元組中找出最大和最小 K 元素時,可以使用“sorted”方法對元素進行排序,然後列舉它們,最後獲取第一個和最後一個元素。

以下是相同程式碼的演示:

示例

 即時演示

my_tuple = (7, 25, 36, 9, 6, 8)

print("The tuple is : ")
print(my_tuple)

K = 2
print("The value of K has been initialized to ")
print(K)
my_result = []
my_tuple = list(my_tuple)
temp = sorted(my_tuple)

for idx, val in enumerate(temp):
   if idx < K or idx >= len(temp) - K:
      my_result.append(val)
my_result = tuple(my_result)

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

輸出

The tuple is :
(7, 25, 36, 9, 6, 8)
The value of K has been initialized to
2
The result is :
(6, 7, 25, 36)

解釋

  • 定義元組,並顯示在控制檯上。

  • 定義 K 的值。

  • 定義一個空列表。

  • 元組轉換為列表。

  • 對其進行排序並存儲在變數中。

  • 對其進行迭代,如果小於 K 或大於列表長度和 K 之間的差,則將其附加到空列表。

  • 這是顯示在控制檯上的輸出。

更新日期:17-Apr-2021

1K+瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.