gpt4 book ai didi

arrays - 在 Go 中创建具有大间隔的范围 slice

转载 作者:数据小太阳 更新时间:2023-10-29 03:39:08 25 4
gpt4 key购买 nike

我想在 Go 中得到一个如下所示的 slice :

[100, 200, 300, 400, 500]

在 Python 中我会这样做:

l = range(100, 600, 100)

我知道我可以在 Go 中做到这一点:

l := []int{}
for i:=100; i<600; i+=100{
l = append(l, i)
}

但是创建这个 slice 没有更简单的方法吗?

最佳答案

像 Python 一样做:

func pyrange(start, end, step int) []int {
// TODO: Error checking to make sure parameters are all valid,
// else you could get divide by zero in make and other errors.

rtn := make([]int, 0, (end-start)/step)
for i := start; i < end; i += step {
rtn = append(rtn, i)
}
return rtn
}

有一个函数。

显然,只有当您需要经常这样做时才值得花时间。默认情况下 Go 不包含这样的函数,因此如果需要,您需要自己编写(或寻找第三方库)。

关于arrays - 在 Go 中创建具有大间隔的范围 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46066204/

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