Python – 提取具有 Range 元素的元组
给定元组列表,提取具有范围内元素的元组。
Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 5, 6
Output : [(5, 6)]
Explanation : Only 1 tuple lies in range of 5-6.
Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 1, 10
Output : [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)]
Explanation : All lie in specified range.
方法 #1:使用列表理解 + all()
在此,我们使用运算符检查范围内的所有元素,并且 all() 对于包含指定范围内的元组的元组返回 true。
Python3
# Python3 code to demonstrate working of
# Extract tuples with elements in Range
# Using all() + list comprehension
# initializing list
test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
strt, end = 4, 7
# list comprehension to encapsulate in 1 liner
# all() checks for all elements in range
res = [sub for sub in test_list if all(ele >= strt and ele <= end for ele in sub)]
# printing results
print("Filtered tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract tuples with elements in Range
# Using filter() + lambda + all()
# initializing list
test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
strt, end = 4, 7
# list() to get back result as list
# all() checks for all elements in range
res = list(filter(lambda sub : all(ele >= strt and ele <= end for ele in sub), test_list))
# printing results
print("Filtered tuples : " + str(res))
输出
The original list is : [(4, 5, 7), (5, 6), (3, 8, 10), (4, 10)]
Filtered tuples : [(4, 5, 7), (5, 6)]
方法 #2:使用 filter() + lambda + all()
在此,我们使用 filter() 根据 lambda 提供的函数提取元组,并使用 all() 作为工具来测试范围元组中的所有元素。
Python3
# Python3 code to demonstrate working of
# Extract tuples with elements in Range
# Using filter() + lambda + all()
# initializing list
test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
strt, end = 4, 7
# list() to get back result as list
# all() checks for all elements in range
res = list(filter(lambda sub : all(ele >= strt and ele <= end for ele in sub), test_list))
# printing results
print("Filtered tuples : " + str(res))
输出
The original list is : [(4, 5, 7), (5, 6), (3, 8, 10), (4, 10)]
Filtered tuples : [(4, 5, 7), (5, 6)]