gpt4 book ai didi

csv - 如何使用Go按字母顺序排列csv文件?

转载 作者:行者123 更新时间:2023-12-01 22:34:48 25 4
gpt4 key购买 nike

我正在尝试使用Go来按字母顺序排序具有一系列名称的.csv文件,该名称基于第一列中的姓氏。我已经搜遍了所有的地方,但似乎找不到找到解决方法的方法。在保持同一行中的其他值的同时,有没有办法做到这一点?
我有三个具有相同名称的.csv文件,但是为了完成我的任务(随机表就座算法),我必须对其进行洗牌。我希望能够将它们重新设置为定义的字母顺序,以便可以确保人们不会连续坐在一起。

提前致谢。 :)

编辑:可能值得展示我用来改组的功能:

func Shuffle(slice []Person) []Person {
r := rand.New(rand.NewSource(time.Now().Unix()))
ret := make([]Person, len(slice))
n := len(slice)
for i := 0; i < n; i++ {
randIndex := r.Intn(len(slice))
ret[i] = slice[randIndex]
slice = append(slice[:randIndex], slice[randIndex+1:]...)
}
return ret

Person [] slice 只是一个包含名字和姓氏的结构。

最佳答案

Go的sort包随附了great example。查看修改后的实现,该实现应满足您的要求。

package main

import (
"encoding/csv"
"fmt"
"io"
"log"
"sort"
"strings"
)

// Unsorted sample data
var unsorted = `Balaam,Wileen,Saint Louis
Meachan,Lothaire,Lefengzhen
Scoggin,Ivonne,Pag
Hawarden,Audrye,Leiria
Claypool,Biddy,Maiorca
Stanford,Douglas,Báguanos
Petriello,Yvor,Obryte
Hatter,Margette,Luoping
Pepall,Linzy,Hucun
Carter,Kit,Parungjawa
`

type Person struct {
Lastname string
Firstname string
City string
}

// Create a new Person record from a given string slice
func NewPerson(fields []string) (p Person, err error) {
if len(fields) < 3 {
return p, fmt.Errorf("not enough data for Person")
}
p.Lastname = fields[0]
p.Firstname = fields[1]
p.City = fields[2]
return
}

// ByLastname implements sort.Interface for []Person based on the Lastname field.
type ByLastname []Person

func (a ByLastname) Len() int { return len(a) }
func (a ByLastname) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByLastname) Less(i, j int) bool { return a[i].Lastname < a[j].Lastname }

func main() {
// Open unsorted CSV from string
r := csv.NewReader(strings.NewReader(unsorted))

var people []Person

for {
// Read CSV line by line
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}

// Create Person from line in CSV
person, err := NewPerson(record)
if err != nil {
continue
}
people = append(people, person)
}

// Sort CSV by Lastname
sort.Sort(ByLastname(people))

// Print to stdout
for _, p := range people {
fmt.Printf("%s %s from %s\n", p.Lastname, p.Firstname, p.City)
}

// Here you would write your CSV
}

关于csv - 如何使用Go按字母顺序排列csv文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60119743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com