英文:
Create slice of range with large intervals in Go
问题
我想在Go语言中创建一个类似这样的切片:
[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)
}
但是有没有更简单的方法来创建这个切片呢?
英文:
I want to get a slice in Go which looks like this:
[100, 200, 300, 400, 500]
In Python I would do this:
l = range(100, 600, 100)
I know I can do this in Go:
l := []int{}
for i:=100; i<600; i+=100{
l = append(l, i)
}
but isn't there anything simpler to create this slice?
答案1
得分: 3
按照Python的方式来做:
func pyrange(start, end, step int) []int {
// TODO: 错误检查以确保参数都有效,否则可能在make和其他地方出现除以零的错误。
rtn := make([]int, 0, (end-start)/step)
for i := start; i < end; i += step {
rtn = append(rtn, i)
}
return rtn
}
使用一个函数。
显然,只有在经常需要这样做时才值得花时间。默认情况下,Go语言不包含这样的函数,所以如果你需要的话,你需要自己编写一个(或者找一个第三方库)。
英文:
Do it the same way Python does:
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
}
With a function.
Obviously only worth the time if you need to do this often. By default Go does not include a function like this, so you need to write your own (or find a third party library) if you want one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论