动态地将每个值附加到2D切片中。

huangapple go评论85阅读模式
英文:

Dynamically append each values into 2D slice

问题

我希望有一个数据结构(数组或切片)看起来像这样:

[[a b c d e][f g h i j] [k l m n o]

[u v w x y]]

其中,a是从"A"到"A"节点的距离(应为0),
b是从"A"到"B"节点的距离,
c是从"A"到"C"节点的距离,

f是从"B"到"A"节点的距离,
g是从"B"到"B"节点的距离(应为0),
h是从"B"到"C"节点的距离。

现在,我创建了一个切片:var shortestPathSLice = make([][]int, 5)来存储这个二维数据。

在我的函数的for循环中,我尝试动态填充这个切片,如下所示:

shortestPathSLice = append(shortestPathSLice[0][index], lowEstimate[0])

其中,lowestimate[0]是两个节点之间最小距离的值。

然而,我遇到了这个错误:append的第一个参数必须是切片;而现在是int类型

有人能告诉我如何在切片的每个元素中动态追加值吗?

代码

var shortestPathSLice = make([][]int, 5)
for index := 0; index < len(t.Location_ids); index++ {
lowEstimate := make([]int, len(priceestimatestruct.Prices))
for i := 0; i < len(priceestimatestruct.Prices); i++ {
lowEstimate[i] = priceestimatestruct.Prices[i].LowEstimate
}

sort.Ints(lowEstimate)
fmt.Println("LowEstimate array: ", lowEstimate)
shortestPathSLice[0] = make([]int, len(lowEstimate))
shortestPathSLice[0][index] = lowEstimate[0]

}

英文:

I wish to have a datastructure(array or slice) to look like this :

[[a b c d e][f g h i j] [k l m n o] 

[u v w x y]]

such that a is the distance between node from "A" to "A" . (which shall be 0)
b is the distance between node from "A" to "B" .
c is the distance between node from "A" to "C" .

f is the distance between node from "B" to "A" .
g is the distance between node from "B" to "B" . (which shall be 0)
h is the distance between node from "B" to "C" .

Now I have created a slice like :
var shortestPathSLice = make([][]int, 5) to store this 2D data.

In my for loop within a function, I am trying to fill this slice dynamically as follows :

shortestPathSLice = append(shortestPathSLice[0][index], lowEstimate[0])

where lowestimate[0] is value of the smallest distances between two nodes.

However, I get an error with this : first argument to append must be slice; have int

Can anyone tell me how can I dynamically append values in EACH ELEMENT in my slice ?

**CODE **

    var shortestPathSLice = make([][]int, 5)
    for index := 0; index &lt; len(t.Location_ids); index++ {
    lowEstimate := make([]int, len(priceestimatestruct.Prices))
    	for i := 0; i &lt; len(priceestimatestruct.Prices); i++ {
    		lowEstimate[i] = priceestimatestruct.Prices[i].LowEstimate
    	}
    
    	sort.Ints(lowEstimate)
    	fmt.Println(&quot;LowEstimate array : &quot;, lowEstimate)
    	shortestPathSLice[0] = make([]int, len(lowEstimate))
    	shortestPathSLice[0][index] = lowEstimate[0]
}

答案1

得分: 4

《Go编程语言规范》

追加和复制切片

内置函数append和copy用于常见的切片操作。对于这两个函数,结果与参数引用的内存是否重叠无关。

可变参数函数append将零个或多个值x追加到类型为S的切片s中,并返回结果切片,类型也为S。值x传递给类型为...T的参数,其中T是S的元素类型,并且适用相应的参数传递规则。作为特例,append还接受可分配给类型[]byte的第一个参数,其后是string类型的第二个参数,然后是...。这种形式追加了字符串的字节。

append(s S, x ...T) S  // T是S的元素类型

如果s的容量不足以容纳额外的值,append会分配一个新的足够大的底层数组,该数组同时适应现有的切片元素和额外的值。否则,append会重用底层数组。

例如,使用append和使用索引:

package main

import "fmt"

func main() {
    { // 使用append
        dim := 5
        matrix := make([][]int, dim) // dim*dim矩阵
        for i := 0; i < dim; i++ {
            matrix[i] = make([]int, 0, dim)
            vector := make([]int, dim)
            for j := 0; j < dim; j++ {
                vector[j] = i*dim + j
                matrix[i] = append(matrix[i], vector[j])
            }
        }
        fmt.Println(matrix)
    }
    { // 使用索引
        dim := 5
        matrix := make([][]int, dim) // dim*dim矩阵
        for i := range matrix {
            matrix[i] = make([]int, dim)
            vector := make([]int, dim)
            for j := range matrix[i] {
                vector[j] = i*dim + j
                matrix[i][j] = vector[j]
            }
        }
        fmt.Println(matrix)
    }
}

输出:

[[0 1 2 3 4] [5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]]
[[0 1 2 3 4] [5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]]
英文:

> The Go Programming Language Specification
>
> Appending to and copying slices
>
> The built-in functions append and copy assist in common slice
> operations. For both functions, the result is independent of whether
> the memory referenced by the arguments overlaps.
>
> The variadic function append appends zero or more values x to s of
> type S, which must be a slice type, and returns the resulting slice,
> also of type S. The values x are passed to a parameter of type ...T
> where T is the element type of S and the respective parameter passing
> rules apply. As a special case, append also accepts a first argument
> assignable to type []byte with a second argument of string type
> followed by .... This form appends the bytes of the string.
>
> append(s S, x ...T) S // T is the element type of S
>
> If the capacity of s is not large enough to fit the additional values,
> append allocates a new, sufficiently large underlying array that fits
> both the existing slice elements and the additional values. Otherwise,
> append re-uses the underlying array.

For example, using append and using an index,

package main

import &quot;fmt&quot;

func main() {
	{ // using append
		dim := 5
		matrix := make([][]int, dim) // dim*dim matrix
		for i := 0; i &lt; dim; i++ {
			matrix[i] = make([]int, 0, dim)
			vector := make([]int, dim)
			for j := 0; j &lt; dim; j++ {
				vector[j] = i*dim + j
				matrix[i] = append(matrix[i], vector[j])
			}
		}
		fmt.Println(matrix)
	}
	{ // using index
		dim := 5
		matrix := make([][]int, dim) // dim*dim matrix
		for i := range matrix {
			matrix[i] = make([]int, dim)
			vector := make([]int, dim)
			for j := range matrix[i] {
				vector[j] = i*dim + j
				matrix[i][j] = vector[j]
			}
		}
		fmt.Println(matrix)
	}
}

Output:

[[0 1 2 3 4] [5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]]
[[0 1 2 3 4] [5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]]

huangapple
  • 本文由 发表于 2015年11月20日 18:46:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/33824711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定