我是iOS开发者&我的项目中有JSON文件。我从保存如下的文件
中获取JSON数组["fa", "pinfield", [
[0, 0, 26082730, ["pt", 213.3332769870769, 584.3332864443584, 414, 226]],
[1, 0, 26082819, ["pt", 0, 0, 414, 226]]
]],
["fa", "pinfield", [
[0, 0, 26084394, ["pt", 195.999944249791, 529.3332950671626, 414, 226]],
[1, 0, 26084475, ["pt", 0, 0, 414, 226]]
]],
["fa", "pinfield", [
[0, 0, 26082219, ["pt", 221.3332726558057, 555.9999453624226, 414, 226]],
[1, 0, 26082310, ["pt", 0, 0, 414, 226]]
]],
["fa", "pinfield", [
[0, 0, 26083275, ["pt", 200.3332853317256, 641.3332811991493, 414, 226]],
[1, 0, 26083364, ["pt", 0, 0, 414, 226]]
]],
["fa", "pinfield", [
[0, 0, 26083755, ["pt", 224.3332901000954, 705.3332707087325, 414, 226]],
[1, 0, 26083836, ["pt", 0, 0, 414, 226]]
]]
此阵列中有五个对象&每个数组都有子数组。
现在有没有办法计算上述值的平均值&放入一个signle数组如下
[" fa"," pinfield",[ [0,0,xxx,[" pt",xxx.xxxxx,xxx.xxxxx,xxx.xxxxx,xxx.xxxxx]], [1,0,xxx,[" pt",0,0,xxx.xxxxx,xxx.xxxxx]] ]
我可以运行循环,但这将是一个时间采取方法。任何帮助都会很棒。
答案 0 :(得分:1)
在某种程度上解决此问题将涉及循环遍历您的数据数组,构建总和和平均值。
您可以使用Swift reduce
高阶函数来构建所有其他值的总和,然后计算最后一步的平均值。
使用reduce
计算更简单数组的总和和平均值的示例:
let array = [1, 7, 14, 35, 14, 12, 17]
let sum = array.reduce(0, +)
let average = Double(sum) / Double(array.count)
print("Sum = \(sum), avrage = \(average)")