1 回答
TA贡献1828条经验 获得超6个赞
只需使用两个映射来存储每个服务器和每个集群的总和。由于您对整个 CSV 文件不感兴趣,而只对某些行感兴趣,因此阅读所有内容有点浪费。只需跳过您不关心的行:
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"strconv"
"strings"
)
func main() {
b := `
,,,,,,,,,,CHARGE,,,,,100.00,,,,,s1.c1
,,,,,,,,,,IGNORE,,,,,,,,,,
,,,,,,,,,,CHARGE,,,,,200.00,,,,,s2.c1
,,,,,,,,,,CHARGE,,,,,300.00,,,,,s3.c2
`
r := csv.NewReader(strings.NewReader(b))
byServer := make(map[string]float64)
byCluster := make(map[string]float64)
for i := 0; ; i++ {
row, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
if row[10] != "CHARGE" {
continue
}
cost, err := strconv.ParseFloat(row[15], 64)
if err != nil {
log.Fatalf("row %d: malformed cost: %v", i, err)
}
xs := strings.SplitN(row[20], ".", 2)
if len(xs) != 2 {
log.Fatalf("row %d: malformed resource name", i)
}
server, cluster := xs[0], xs[1]
byServer[server] += cost
byCluster[cluster] += cost
}
fmt.Printf("byServer: %+v\n", byServer)
fmt.Printf("byCluster: %+v\n", byCluster)
}
// Output:
// byServer: map[s2:200 s3:300 s1:100]
// byCluster: map[c1:300 c2:300]
在操场上试试:https ://play.golang.org/p/1e9mJf4LyYE
- 1 回答
- 0 关注
- 60 浏览
添加回答
举报