这是我的函数,我正在尝试获取所有 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)
Map
元组为其 value
值并用 reduce
求和。
func getSum(myList: [(title: String, id: Int, value: Double)]) -> Double {
return myList.map(\.value).reduce(0.0, +)
}
//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