我有這個代碼
type key struct {
account string
quantity float64
}
type invoice_tag struct {
account string
value_after_discount float64
value float64
price float64
total_discount float64
discount float64
quantity float64
}
invoice := []invoice_tag{{"Cash", 1024, 1024, 1, 0, 0, 1024}, {"Service Revenue", 0, 2048, 2, 0, 0, 1024}, {"Service Revenue", 0, 0, 0, 1024, 1, 1024}}
m := map[key][5]float64{}
for _, i := range invoice {
m[key{i.account, i.quantity}] = [5]float64{i.value_after_discount, i.value, i.price, i.total_discount, i.discount}
}
fmt.Println(m)
我想通過account和quantity和value_after_discount與value_after_discount和value與value和price與與price和total_discount與total_discount和discount與進行分組和總結discount。并且輸出應該是
map[{Cash 1024}:[1024 1024 1 0 0] {Service Revenue 1024}:[1024 2048 2 1024 1]]
https://play.golang.org/p/KKTmovpfN1z
uj5u.com熱心網友回復:
使用結構作為復合鍵account和quantity欄位。注意:浮點數比較可能會讓您感到驚訝,如果quantity是整數,您應該使用整數(例如int)!
使用保存要求和的值的結構體。為簡單起見,我將使用invoice_tag它,因為它包含所有必需的欄位,但您也可以根據自己的喜好創建一個單獨的結構。
我將在映射中存盤一個指向這個結構的指標,所以當我在每次迭代中更新它時,我不必存盤新值。
例如:
m := map[key]*invoice_tag{}
for _, i := range invoice {
k := key{i.account, i.quantity}
sums := m[k]
if sums == nil {
sums = &invoice_tag{}
m[k] = sums
}
sums.value_after_discount = i.value_after_discount
sums.value = i.value
sums.price = i.price
sums.total_discount = i.total_discount
sums.discount = i.discount
}
for k, v := range m {
fmt.Printf("key: %v, sums: value_after_discount: %f, value: %f, price: %f, total_discount: %f, discount: %f\n",
k, v.value_after_discount, v.value, v.price, v.total_discount, v.discount)
}
這將輸出(在Go Playground上嘗試):
key: {Cash 1024}, sums: value_after_discount: 1024.000000, value: 1024.000000, price: 1.000000, total_discount: 0.000000, discount: 0.000000
key: {Service Revenue 1024}, sums: value_after_discount: 0.000000, value: 2048.000000, price: 2.000000, total_discount: 1024.000000, discount: 1.000000
再次:這是有效的,因為我們使用的輸入資料包含相同的浮點常量文字(導致相同的float64值)。在實踐中,由于 IEEE 754 浮點怪癖,分組可能會給出不正確的結果。int如果可能,我建議使用數量。如果不可能,則將數量格式化為相同的格式(包括某些數字四舍五入)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/339719.html
上一篇:Spring資料彈性搜索4.1
