Python - 為元組中的非最大最小元素分配具體值


當需要為元組中的非最大最小元素分配特定值時,可以使用“max”方法、“min”方法、“tuple”方法和一個迴圈。

“max”方法返回可迭代物件中所有元素中的最大值。“min”方法返回可迭代物件中所有元素中的最小值。

“tuple”方法將給定的值/可迭代物件轉換為元組型別。

以下是對其進行演示 −

示例

 線上演示

my_tuple = (25, 56, 78, 91, 23, 11, 0, 99, 32, 10)
print("The tuple is : ")
print(my_tuple)
K = 5
print("K has been assigned to " + str(K))
my_result = []
for elem in my_tuple:
   if elem not in [max(my_tuple), min(my_tuple)]:
      my_result.append(K)
   else:
      my_result.append(elem)
      my_result = tuple(my_result)
print("The tuple after conversion is : " )
print(my_result)

輸出

The tuple is :
(25, 56, 78, 91, 23, 11, 0, 99, 32, 10)
K has been assigned to 5
The tuple after conversion is :
(5, 5, 5, 5, 5, 5, 0, 99, 5, 5)

說明

  • 定義元組並顯示在控制檯上。
  • 定義並顯示“K”的值。
  • 建立一個空列表。
  • 迭代元組,並確定最大值和最小值。
  • 如果這些值不在元組中,則將它們附加到空列表。
  • 將此列表轉換為元組。
  • 然後將其顯示為控制檯上的輸出。

更新於:2021-03-11

90 次瀏覽

開啟你的 職業道路

透過完成課程獲得認證

開始學習
廣告