在Go语言中创建具有大间隔的范围切片可以使用以下方式:

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

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&lt;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 &lt; 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.

huangapple
  • 本文由 发表于 2017年9月6日 11:13:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/46066204.html
匿名

发表评论

匿名网友

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

确定