Python – 在元组中获取偶数索引元素
有时,在处理Python数据时,可能会遇到一个问题,即我们需要执行仅提取元组中的索引元素的任务。这种问题非常普遍,可以在许多领域都有可能的应用,例如日间编程。让我们讨论可以执行此任务的某些方式。
Input : test_tuple = (1, 2, 4, 5, 6)
Output : (1, 4, 6)
Input : test_tuple = (1, 2, 4)
Output : (1, 4)
方法 #1:使用tuple() + generator expression + enumerate()
上述功能的组合可以用来解决这个问题。在此,我们使用生成器表达式执行迭代任务,使用 enumerate() 检查偶数索引并使用 tuple() 将结果转换为元组。
# Python3 code to demonstrate working of
# Extract Even indexed elements in Tuple
# Using tuple() + generator expression + enumerate()
# initializing tuples
test_tuple = (5, 'Gfg', 2, 8.8, 1.2, 'is')
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Extract Even indexed elements in Tuple
# Using tuple() + generator expression + enumerate()
res = tuple(ele for idx, ele in enumerate(test_tuple) if idx % 2 == 0)
# printing result
print("The even indexed elements : " + str(res))
输出 :
The original tuple : (5, 'Gfg', 2, 8.8, 1.2, 'is')
The even indexed elements : (5, 2, 1.2)
方法#2:使用递归
这是可以执行此任务的另一种方式。在此,我们进入recur。函数新列表并提取初始元素并再次传递列表直到列表末尾,仅提取偶数索引元素。
# Python3 code to demonstrate working of
# Extract Even indexed elements in Tuple
# Using recursion
def helper_fnc(test_tuple):
if len(test_tuple) == 0 or len(test_tuple) == 1:
return ()
return (test_tuple[0], ) + helper_fnc(test_tuple[2:])
# initializing tuples
test_tuple = (5, 'Gfg', 2, 8.8, 1.2, 'is')
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Extract Even indexed elements in Tuple
# Using recursion
res = helper_fnc(test_tuple)
# printing result
print("The even indexed elements : " + str(res))
输出 :
The original tuple : (5, 'Gfg', 2, 8.8, 1.2, 'is')
The even indexed elements : (5, 2, 1.2)