gpt4 book ai didi

dictionary - 从 slice 图中删除重复项

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

我有一张 slice 图,需要从中删除重复项。我认为我已经接近解决方案,但我错过了一些我无法弄清楚的东西。

预期输出:map[key1:[1 2 3] key2:[1 2 3]]

实际输出:map[key2:[1 2 3]]

    package main

import "fmt"

func main() {
x := make(map[string][]string)
keys := make(map[string]bool)
result := make(map[string][]string)

x["key1"] = append(x["key1"], "1")
x["key1"] = append(x["key1"], "1")
x["key1"] = append(x["key1"], "2")
x["key1"] = append(x["key1"], "3")
x["key1"] = append(x["key1"], "3")
x["key2"] = append(x["key2"], "1")
x["key2"] = append(x["key2"], "2")
x["key2"] = append(x["key2"], "2")
x["key2"] = append(x["key2"], "3")

fmt.Println(x)

for k, e := range x{
for _, v := range e {
if _, val := keys[v]; !val {
keys[v] = true
result[k] = append(result[k], v)
}
}
}
fmt.Println(result)
}

Playground 上的示例:Go Playground

最佳答案

您希望单独处理所有 slice 。例如。您想要从 x["key1"] 表示的 slice 中删除重复项,并且想要从 x["key2"] 表示的 slice 中删除重复项。这意味着您应该在处理新 slice 时“重置”keys,但您只初始化一次。

因此,如果(无论如何)您首先处理 x["key1"],然后继续处理 x["key2"],因为x["key1"] 包含了 x["key2"] 包含的所有元素,不会找到新元素,因此 "key2" 将完全从结果中排除。

只需在循环内的每个 slice 之前初始化:

for k, e := range x {
keys := make(map[string]bool)
for _, v := range e {
if _, val := keys[v]; !val {
keys[v] = true
result[k] = append(result[k], v)
}
}
}

这样,输出将是(在 Go Playground 上尝试):

map[key1:[1 1 2 3 3] key2:[1 2 2 3]]
map[key1:[1 2 3] key2:[1 2 3]]

另请注意,您可以使用 composite literal以紧凑的方式创建初始 map ,如下所示:

x := map[string][]string{
"key1": {"1", "1", "2", "3", "3"},
"key2": {"1", "2", "2", "3"},
}

由于您在 keys 映射中使用 bool ,您可以简单地检查像这样的现有元素(因为使用不在其中的键对映射进行索引会导致在 map 值类型的零值中,对于 bool 来说是 false,正确地告诉元素不在 map 中):

if !keys[v] {
keys[v] = true
result[k] = append(result[k], v)
}

Go Playground 上试试这个.

您可以在这里阅读更多相关信息:How to check if a map contains a key in Go? ;和 How can I create an array that contains unique strings?

关于dictionary - 从 slice 图中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58613879/

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