Python – 元组上的备用元素操作
有时,在使用Python元组时,我们可能会遇到需要对提取的元组交替链执行操作的问题。这种操作可以在许多领域都有应用,例如Web开发。让我们讨论可以执行此任务的某些方式。
Input : test_tuple = (5, 6, 3)
Output :
The alternate chain sum 1 : 6
The alternate chain sum 2 : 8
Input : test_tuple = (5, 6)
Output :
The alternate chain sum 1 : 6
The alternate chain sum 2 : 5
方法 #1:使用循环 + enumerate()
上述功能的组合为这个问题提供了强力解决方案。在此,我们使用 enumerate() 提取元素和索引,并使用条件执行链接。
# Python3 code to demonstrate working of
# Alternate Elements operation on Tuple
# Using loop + enumerate()
# initializing tuple
test_tuple = (5, 6, 3, 6, 10, 34)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Alternate Elements operation on Tuple
# Using loop + enumerate()
sum1 = 0
sum2 = 0
for idx, ele in enumerate(test_tuple):
if idx % 2:
sum1 += ele
else :
sum2 += ele
# printing result
print("The alternate chain sum 1 : " + str(sum1))
print("The alternate chain sum 2 : " + str(sum2))
输出 :
The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 46
The alternate chain sum 2 : 18
方法#2:使用列表切片
这个问题也可以使用切片操作来解决。在此,我们使用列表切片技术执行提取备用链的任务。
# Python3 code to demonstrate working of
# Alternate Elements operation on Tuple
# Using list slicing
# initializing tuple
test_tuple = (5, 6, 3, 6, 10, 34)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# Alternate Elements operation on Tuple
# Using list slicing
sum1 = sum(test_tuple[1::2])
sum2 = sum(test_tuple[0::2])
# printing result
print("The alternate chain sum 1 : " + str(sum1))
print("The alternate chain sum 2 : " + str(sum2))
输出 :
The original tuple : (5, 6, 3, 6, 10, 34)
The alternate chain sum 1 : 46
The alternate chain sum 2 : 18