📜  Python - 双元组交替求和

📅  最后修改于: 2022-05-13 01:55:01.025000             🧑  作者: Mango

Python - 双元组交替求和

给定双元组,交替执行交替元素的求和,即索引的求和。

方法#1:使用循环

在这里,我们遍历每个元组,并检查列表中的索引,如果偶数,则对元组的第一个元素求和,否则将第二个元素相加以计算总和。

Python3
# Python3 code to demonstrate working of
# Dual Tuple Alternate summation
# Using loop
  
# initializing list
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
res = 0
for idx in range(len(test_list)):
  
    # checking for Alternate element
    if idx % 2 == 0:
        res += test_list[idx][0]
    else:
        res += test_list[idx][1]
  
# printing result
print("Summation of Alternate elements of tuples : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Dual Tuple Alternate summation
# Using list comprehension + sum()
  
# initializing list
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# summation using sum(), list comprehension offers shorthand
res = sum([test_list[idx][0] if idx % 2 == 0 else test_list[idx][1] for idx in range(len(test_list))])
  
# printing result 
print("Summation of Alternate elements of tuples : " + str(res))


输出
The original list is : [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
Summation of Alternate elements of tuples : 19

方法 #2:使用列表理解 + sum()

在这里,我们使用sum()执行求和任务,并且使用列表理解为列表中的元组迭代提供紧凑的解决方案。

蟒蛇3

# Python3 code to demonstrate working of 
# Dual Tuple Alternate summation
# Using list comprehension + sum()
  
# initializing list
test_list = [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# summation using sum(), list comprehension offers shorthand
res = sum([test_list[idx][0] if idx % 2 == 0 else test_list[idx][1] for idx in range(len(test_list))])
  
# printing result 
print("Summation of Alternate elements of tuples : " + str(res))
输出
The original list is : [(4, 1), (5, 6), (3, 5), (7, 5), (1, 10)]
Summation of Alternate elements of tuples : 19