gpt4 book ai didi

go - 结构体数组去重复

转载 作者:行者123 更新时间:2023-12-02 23:35:57 26 4
gpt4 key购买 nike

我有一个结构数组,我想删除所有重复元素,但保留数组中的最后一个元素。类似于 hashmap 的东西,我可以将每次匹配的最后一个结构更新为新数组

我有一个类似这样的结构

type samplestruct struct {
value1 string
value2 string
value3 string
value4 string
value5 string
}

在我的结构数组中,如果任何结构的 value1、value2 和 value3 相同,则删除所有重复项并保留最后一个结构。

func unique(sample []samplestruct) []samplestruct {
var unique []samplestruct

for _, v := range sample {
skip := false
for _, u := range unique {
if v.value1 == u.value1 && v.value2 == u.value2 && v.value3 == u.value3 {
skip = true
break
}
}
if !skip {
unique = append(unique, v)
}
}
return unique

}

此代码返回与所提供的条件匹配的第一个结构,但我想要与条件匹配的最后一个结构

给定输入 -

[
samplestruct{"ram","rahim","india","34","india"},
samplestruct{"ram","rahim","india","38","America"},
samplestruct{"ram","rahim","india","40","Jamica"},
samplestruct{"amit","rawat","bangladesh","35","hawai"},
samplestruct{"amit","rawat","bangladesh","36","india"}
]

预期输出 -

[
samplestruct{"ram","rahim","india","40","Jamica"},
samplestruct{"amit","rawat","bangladesh","36","india"}
]

最佳答案

问题中的代码已经差不多了。当在 unique 中找到匹配元素时,用当前值覆盖该元素:

func unique(sample []samplestruct) []samplestruct {
var unique []samplestruct
sampleLoop:
for _, v := range sample {
for i, u := range unique {
if v.value1 == u.value1 && v.value2 == u.value2 && v.value3 == u.value3 {
unique[i] = v
continue sampleLoop
}
}
unique = append(unique, v)
}
return unique
}

其他答案中显示的基于 map 的方法可能更合适,具体取决于数据集的大小和幸存元素的数量。这是 map 方法的正确实现:

func unique(sample []samplestruct) []samplestruct {
var unique []samplestruct
type key struct{ value1, value2, value3 string }
m := make(map[key]int)
for _, v := range sample {
k := key{v.value1, v.value2, v.value3}
if i, ok := m[k]; ok {
// Overwrite previous value per requirement in
// question to keep last matching value.
unique[i] = v
} else {
// Unique key found. Record position and collect
// in result.
m[k] = len(unique)
unique = append(unique, v)
}
}
return unique
}

关于go - 结构体数组去重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57706801/

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