Python – 过滤连续元素元组
给定一个元组列表,过滤由连续元素组成的元组,即 diff 为 1。
Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 4), (6, 4, 6, 3)]
Output : [(3, 4, 5, 6)]
Explanation : Only 1 tuple adhers to condition.
Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
Output : [(3, 4, 5, 6), (1, 2, 3)]
Explanation : Only 2 tuples adher to condition.
方法#1:使用循环
在此,对于每个元组,我们调用连续元素实用程序,如果元组是连续的,则返回 True。
Python3
# Python3 code to demonstrate working of
# Filter consecutive elements Tuples
# Using loop
# hlpr_func
def consec_check(tup):
for idx in range(len(tup) - 1):
# returns false if any element is not consec.
if tup[idx + 1] != tup[idx] + 1:
return False
return True
# initializing list
test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
# printing original list
print("The original list is : " + str(test_list))
res = []
for sub in test_list:
# calls fnc to check consec.
if consec_check(sub):
res.append(sub)
# printing result
print("The filtered tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter consecutive elements Tuples
# Using list comprehension
# hlpr_func
def consec_check(tup):
for idx in range(len(tup) - 1):
# returns false if any element is not consec.
if tup[idx + 1] != tup[idx] + 1:
return False
return True
# initializing list
test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
# printing original list
print("The original list is : " + str(test_list))
# one-liner to solve problem, using list comprehension
res = [sub for sub in test_list if consec_check(sub)]
# printing result
print("The filtered tuples : " + str(res))
输出
The original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
方法#2:使用列表推导
在此,我们执行与上述类似的函数,只是使用列表理解的单行速记。
Python3
# Python3 code to demonstrate working of
# Filter consecutive elements Tuples
# Using list comprehension
# hlpr_func
def consec_check(tup):
for idx in range(len(tup) - 1):
# returns false if any element is not consec.
if tup[idx + 1] != tup[idx] + 1:
return False
return True
# initializing list
test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
# printing original list
print("The original list is : " + str(test_list))
# one-liner to solve problem, using list comprehension
res = [sub for sub in test_list if consec_check(sub)]
# printing result
print("The filtered tuples : " + str(res))
输出
The original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]