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。
在方法外部,定义了一个元组列表并在控制台上显示。
定义了一个空列表。
迭代元组列表,并通过将每个元组传递给它来调用该方法。
其结果将附加到空列表中。
此列表将作为输出显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP