1 回答

TA贡献1906条经验 获得超3个赞
您可以为 sort.Sort 添加一些方法来调用和排序您的数据。您的数据的第一列似乎是格式为 MMDDYYYY 的日期。
package main
import (
"fmt"
"sort"
"time"
)
type CSV [][]string
// Determine if one CSV line at index i comes before the line at index j.
func (data CSV) Less(i, j int) bool {
dateColumnIndex := 0
date1 := data[i][dateColumnIndex]
date2 := data[j][dateColumnIndex]
timeT1, _ := time.Parse("01022006", date1)
timeT2, _ := time.Parse("01022006", date2)
return timeT1.Before(timeT2)
}
// Other functions required for sort.Sort.
func (data CSV) Len() int {
return len(data)
}
func (data CSV) Swap(i, j int) {
data[i], data[j] = data[j], data[i]
}
func main() {
data := [][]string{
[]string{"05111985", "0.33", "0.34", "0.33"},
[]string{"11051999", "1.60", "1.65", "1.56"},
[]string{"12021986", "0.43", "0.43", "0.42"},
}
// Sort the data in place using the methods above.
sort.Sort(CSV(data))
fmt.Println(data)
}
输出:[[05111985 0.33 0.34 0.33] [12021986 0.43 0.43 0.42] [11051999 1.60 1.65 1.56]].
- 1 回答
- 0 关注
- 122 浏览
添加回答
举报