我具有以下结构。
struct Fruit {
var name: String
var stateCd: Int
var amt: Int
var cumulativeAvg: Int
}
var fruit = [
Fruit(name: "apple", stateCd: 0, amt: 100, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 0, amt: 200, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 1, amt: 100, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 0, amt: 300, cumulativeAvg: 0)
]
我想要的是,如果stateCd为零,则将cumulativeAvg列的值更改为累积平均值。 如果stateCd为1,则采用先前的平均值而不累加总和。
更改后的值预计如下。
Fruit(name: "apple", stateCd: 0, amt: 100, cumulativeAvg: 100),
Fruit(name: "apple", stateCd: 0, amt: 200, cumulativeAvg: 150),
Fruit(name: "apple", stateCd: 1, amt: 100, cumulativeAvg: 150),
Fruit(name: "apple", stateCd: 0, amt: 300, cumulativeAvg: 200)
答案 0 :(得分:1)
一个简单的for循环可以做到
var sum = 0
var count = 0
for i in 0..<fruit.count
{
if(fruit[i].stateCd == 0)
{
count += 1
sum += fruit[i].amt
fruit[i].cumulativeAvg = sum/count
}
else if(fruit[i].stateCd == 1)
{
fruit[i].cumulativeAvg = sum/count
}
}
答案 1 :(得分:1)
这将是解决您问题的更好,更清洁的方法。
struct Fruit {
var name: String
var stateCd: Int
var amt: Double
var cumulativeAvg: Double
}
创建另一个结构来存储特定水果的计数和平均值。
struct FruitStats {
var count: Double
var average: Double
}
维护一个字典,该字典跟踪每个水果的计数和平均值。
var fruitStats: [String: FruitStats] = [:]
var fruits = [
Fruit(name: "apple", stateCd: 0, amt: 100, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 0, amt: 200, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 1, amt: 100, cumulativeAvg: 0),
Fruit(name: "apple", stateCd: 0, amt: 300, cumulativeAvg: 0),
Fruit(name: "orange", stateCd: 0, amt: 100, cumulativeAvg: 0),
Fruit(name: "orange", stateCd: 1, amt: 100, cumulativeAvg: 0),
Fruit(name: "orange", stateCd: 0, amt: 400, cumulativeAvg: 0)
]
let newFruits = fruits.map { (fruit) -> Fruit in
var newFruit = fruit
var fruitStat = fruitStats[fruit.name, default: FruitStats(count: 0, average: 0)]
if fruit.stateCd == 0 {
fruitStat.average *= fruitStat.count
fruitStat.count += 1
fruitStat.average = (fruitStat.average + fruit.amt)/fruitStat.count
}
newFruit.cumulativeAvg = fruitStat.average
fruitStats[fruit.name] = fruitStat
return newFruit
}
for fruit in newFruits {
print(fruit.name, "\t", fruit.stateCd, fruit.amt, fruit.cumulativeAvg)
}
apple 0 100.0 100.0 apple 0 200.0 150.0 apple 1 100.0 150.0 apple 0 300.0 200.0 orange 0 100.0 100.0 orange 1 100.0 100.0 orange 0 400.0 250.0
答案 2 :(得分:0)
fruit[0].cumulativeAvg = fruit[0].amt
for (i, f) in zip(1..., fruit.dropFirst()) {
if f.stateCd == 1 {
fruit[i].cumulativeAvg = fruit[i-1].cumulativeAvg
} else {
fruit[i].cumulativeAvg = (fruit[i-1].cumulativeAvg * i + fruit[i].amt) / (i+1)
}
}