如何获取元组数组中所有 Double 值的总和? [重复]

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

这是我的函数,我正在尝试获取所有 Double 值的总和。我尝试使用 += 但遇到了很多错误,我非常感谢任何帮助!

 func getSum(myList: [(title: String, id: Int, value: Double)]) -> Double {
    
    var key = Double()

    for i in 0..<myList.count {
         //something over here needs to change
        key = myList[i].value
        
    }

     
    
    return key
}


let myList: [(String, Int, Double)] = [("A", 1, 1.5), ("B", 2, 2.5), ("C", 3, 3.5)] // should return 7.5 (1.5 + 2.5 + 3.5)
arrays swift tuples
2个回答
3
投票

Map
元组为其
value
值并用
reduce
求和。

func getSum(myList: [(title: String, id: Int, value: Double)]) -> Double {
    return myList.map(\.value).reduce(0.0, +)
}

-1
投票
//Python Version 3.8

from typing import List, Tuple

def get_sum(my_list: List[Tuple[str, int, float]]) -> float:
    total = 0.0
for _, _, value in my_list:
    total += value
return total

my_list = [("A", 1, 1.5), ("B", 2, 2.5), ("C", 3, 3.5)]

result = get_sum(my_list)
print(result)   //Output Result 7.5
© www.soinside.com 2019 - 2024. All rights reserved.