Python - 刪除元組,其差值大於 K


當需要刪除元組,其差值大於 K 時,可使用 abs() 方法。

以下是演示:

示例

my_tuple = [(41, 18), (21,57), (39, 22), (23, 42), (22, 10)]
print("The tuple is :")
print(my_tuple)
K = 20
my_result = [element for element in my_tuple if abs(element[0] - element[1]) <= K]
print("The result is :")
print(my_result)

The tuple is :
[(41, 18), (21, 57), (39, 22), (23, 42), (22, 10)]
The result is :
[(39, 22), (23, 42), (22, 10)]

說明

  • 定義一個元組並將其顯示在控制檯中。

  • 定義 K 的值。

  • 使用列表推導來遍歷此列表,並比較元組中每個元素的差值與 K。

  • 此結果被分配給了一個變數。

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

更新於: 08-9 月-2021

100 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.