我有一个如下数组:
var array: [Double] = [4, 5, 2, 4, 3, 6]
我想做的是从该数组创建一个新数组,其中包含每个值与其上一个值相比的百分比差异。所以我上面的数组看起来像:
var newArray = [0, 25, -60, 100, -25, 100]
这是否有意义?非常感谢您的帮助,非常感谢!
答案 0 :(得分:6)
这可以方便地用zip()
来枚举成对
相邻的数组元素:
let array: [Double] = [4, 5, 2, 4, 3, 6]
let percentages = [0] + zip(array, array.dropFirst()).map {
(old, new) in
return 100.0 * (new - old) / old
}
print(percentages) // [0.0, 25.0, -60.0, 100.0, -25.0, 100.0]
(假设所有数组元素都不为零。)
或使用简写语法:
let percentages = [0] + zip(array, array.dropFirst()).map {
100.0 * ($1 - $0) / $0
}
答案 1 :(得分:2)
您可以使用var保留最后一个元素的引用,并使用defer在map中更新它:
extension Collection where Element: FloatingPoint {
var percentageDifference: [Element] {
guard var last = first else { return [] }
return map { element in
defer { last = element }
return (element - last) / last * 100
}
}
}
let numbers: [Double] = [4, 5, 2, 4, 3, 6]
let percentageDifference = numbers.percentageDifference
print(percentageDifference) // "[0.0, 25.0, -60.0, 100.0, -25.0, 100.0]\n"
答案 2 :(得分:1)
您可以这样做:
func percentageDifference(num1: Double, num2: Double) -> Double {
return (num2 - num1) / num1 * 100
}
var array: [Double] = [4, 5, 2, 4, 3, 6]
var resultArray: [Double] = [0]
for i in (1..<array.count) {
resultArray.append(percentageDifference(num1: array[i-1], num2: array[i]))
}
答案 3 :(得分:1)
单线:您可以遍历索引并计算结果:
let array: [Double] = [4, 5, 2, 4, 3, 6]
let newArray = array.indices.map { i in (array[i] - array[max(0,i-1)]) / array[max(0, i-1)] * 100.0 }
print(newArray) // [0.0, 25.0, -60.0, 100.0, -25.0, 100.0]
有一个小的代码重复,但是它以一种高效的方式工作,我想说:)