Python – 過濾元組中的連續元素


如果需要從元組列表篩選連續的元素,則定義一個將元組列表作為引數並檢查每個元組的索引的方法,根據索引返回布林值。

示例

以下是相同的演示示例:-

print("Method definition begins...")
def check_consec_tuple_elem(my_tuple):
   for idx in range(len(my_tuple) - 1):
      if my_tuple[idx + 1] != my_tuple[idx] + 1:
         return False
   return True
print("Method definition ends...")
my_tuple = [(23, 24, 25, 26), (65, 66, 78, 29), (11, 28, 39), (60, 61, 62, 63)]

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

my_result = []

for elem in my_tuple:
   if check_consec_tuple_elem(elem):
      my_result.append(elem)

print("The resultant tuple is : ")
print(my_result)

輸出

Method definition begins...
Method definition ends...
The list of tuple is :
[(23, 24, 25, 26), (65, 66, 78, 29), (11, 28, 39), (60, 61, 62, 63)]
The resultant tuple is :
[(23, 24, 25, 26), (60, 61, 62, 63)]

解釋

  • 定義了一個名為“check_consec_tuple_elem”的方法,該方法將一個元組作為引數。

  • 它遍歷元組並檢查索引處的元素和將索引加 1 後的同一個索引處的元素是否相等。

  • 如果不是,它將返回 False。

  • 在方法外部,定義了一個元組列表並在控制檯上顯示。

  • 定義了一個空列表。

  • 迭代元組列表,並透過將每個元組傳遞給它來呼叫該方法。

  • 其結果將附加到空列表中。

  • 此列表將作為輸出顯示在控制檯上。

更新於: 2021-9-13

214 瀏覽次數

啟動你的 職業生涯

完成課程以獲得認證

開始
廣告