GoLang:如何从2D切片中删除元素? [英] GoLang: How to delete an element from a 2D slice?

查看:111
本文介绍了GoLang:如何从2D切片中删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近一直在玩Go,我想看看如何从二维切片中删除元素。

I've recently been messing around with Go and I wanted to see how it would be to delete an element from a two-dimensional slice.

用于删除一维切片中的元素,我可以成功使用:

For deleting an element from a one-dimensional slice, I can successfully use:

data = append(data[:i], data[i+1:]...)

但是,使用二维切片时,使用:

However, with a two-dimensional slice, using:

data = append(data[i][:j], data[i][j+1:]...)

抛出错误:

cannot use append(data[i][:j], data[i][j+1:]...) (type []string) as type [][]string in assignment

要解决这个问题需要其他方法吗?

Would tackling this require a different approach?

推荐答案

Go中的2D切片仅是切片的一部分。因此,如果要从此2D切片中删除一个元素,实际上仍然只需要从一个切片中删除一个元素(这是另一个切片的元素)。

A 2D slice in Go is nothing more than a slice of slices. So if you want to remove an element from this 2D slice, effectively you still only have to remove an element from a slice (which is an element of another slice).

没有更多的参与。唯一需要注意的是,当从行切片中删除元素时,结果将仅是外部切片的行(元素)的新值,而不是2D切片本身。因此,您必须将结果分配给外部切片的元素,以及刚刚删除了该元素的行:

There is nothing more involved. Only thing you have to look out is that when you remove an element from the row-slice, the result will only be the "new" value of the row (an element) of the "outer" slice, and not the 2D slice itself. So you have to assign the result to an element of the outer slice, to the row whose element you just removed:

// Remove element at the ith row and jth column:
s[i] = append(s[i][:j], s[i][j+1:]...)

请注意,如果我们替换 s [i],这与简单的从切片中删除相同。 code>与 a (毫不奇怪,因为 s [i] 表示行切片,其 jth 我们要删除的元素):

Note that this is identical to the simple "removal from slice" if we substitute s[i] with a (not surprisingly, because s[i] denotes the "row-slice" whose jth element we're removing):

a = append(a[:j], a[j+1:]...)

请参见以下完整示例:

See this complete example:

s := [][]int{
    {0, 1, 2, 3},
    {4, 5, 6, 7},
    {8, 9, 10, 11},
}

fmt.Println(s)

// Delete element s[1][2] (which is 6)
i, j := 1, 2
s[i] = append(s[i][:j], s[i][j+1:]...)

fmt.Println(s)

输出(在 转到游乐场 ):

Output (try it on the Go Playground):

[[0 1 2 3] [4 5 6 7] [8 9 10 11]]
[[0 1 2 3] [4 5 7] [8 9 10 11]]

这篇关于GoLang:如何从2D切片中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆