Python – 在嵌套混合元组中提取偶数元素
有时,在使用Python元组时,我们可能会遇到需要从元组中获取所有偶数元素的问题。元组可以嵌套或混合。这种问题可能发生在数据域中。让我们讨论可以执行此任务的某些方式。
Input : test_tuple = (5, (7, 6, (2, (4, ))))
Output : ((6, (2, (4, ))), )
Input : test_tuple = (5, (8, 6, (2, (4, 8))))
Output : ((8, 6, (2, (4, 8))), )
方法 #1:使用递归 + isinstance() + 循环
这是可以执行此任务的方式之一。在此,我们使用 isinstance() 执行使元素实例为整数的任务,一旦遇到元组,该函数就会递归。
Python3
# Python3 code to demonstrate working of
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + loop
# helper_fnc
def even_ele(test_tuple, even_fnc):
res = tuple()
for ele in test_tuple:
if isinstance(ele, tuple):
res += (even_ele(ele, even_fnc), )
elif even_fnc(ele):
res += (ele, )
return res
# initializing tuples
test_tuple = (4, 5, (7, 6, (2, 4)), 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + loop
res = even_ele(test_tuple, lambda x: x % 2 == 0)
# printing result
print("Even elements of tuple : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + generator expression
# helper_fnc
def even_ele(test_tuple, even_fnc):
return tuple(even_ele(ele, even_fnc) if isinstance(ele, tuple) else ele
for ele in test_tuple if isinstance(ele, tuple) or even_fnc(ele))
# initializing tuples
test_tuple = (4, 5, (7, 6, (2, 4)), 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + generator expression
res = even_ele(test_tuple, lambda x: x % 2 == 0)
# printing result
print("Even elements of tuple : " + str(res))
输出 :
The original tuple : (4, 5, (7, 6, (2, 4)), 6, 8)
Even elements of tuple : (4, (6, (2, 4)), 6, 8)
方法 #2:使用递归 + isinstance() + 生成器表达式
此方法以与上述方法类似的方式执行此任务。不同之处在于它是上述方法的简写,使用生成器表达式在一行中完成工作。
Python3
# Python3 code to demonstrate working of
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + generator expression
# helper_fnc
def even_ele(test_tuple, even_fnc):
return tuple(even_ele(ele, even_fnc) if isinstance(ele, tuple) else ele
for ele in test_tuple if isinstance(ele, tuple) or even_fnc(ele))
# initializing tuples
test_tuple = (4, 5, (7, 6, (2, 4)), 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Extract Even elements in Nested Mixed Tuple
# Using recursion + isinstance() + generator expression
res = even_ele(test_tuple, lambda x: x % 2 == 0)
# printing result
print("Even elements of tuple : " + str(res))
输出 :
The original tuple : (4, 5, (7, 6, (2, 4)), 6, 8)
Even elements of tuple : (4, (6, (2, 4)), 6, 8)