如何获取列表中嵌套元组的总和

问题描述 投票:0回答:1

我有列表

[(270,), (270,)]
,我想将元组中的值添加到一起。我该怎么做?

注意:元组的数量会有所不同,因此我需要一个动态解决方案将值添加在一起

python python-3.x list tuples
1个回答
0
投票

假设你有一个元组列表(大小不同),你可以直接使用Python中的

sum
函数:

初始化一个变量来存储总和

total_sum = 0

# Initialize a variable to store the total sum
total_sum = 0

# Iterate through the list and add the values in each tuple to the total sum
for each_tup in tuple_list:
   total_sum += sum(each_tup)

print(total_sum)

© www.soinside.com 2019 - 2024. All rights reserved.