首页 > 解决方案 > 在一系列数字上模仿 Go 中的 Python 列表理解

问题描述

在 Python 中,我可以执行以下操作:

numbers = [i for i in range(5)]

这将导致:

>> [0, 1, 2, 3, 4]

我正在学习 Go,所以我想我会尝试复制这个过程:

package main

import "fmt"

func inRange(num int) []int {
    // Make a slice to hold the number if int's specified
    output := make([]int, num)

    // For Loop to insert data
    for i := 0; i < num; i++ {
        output[i] = i
    }
    return output
}

func main() {
    x := inRange(10)
    fmt.Print(x)
}

输出:

>> [0, 1, 2, 3, 4]

看起来很冗长,有没有更简单的方法可以在 Go 中实现这一点?我也喜欢在 python 中我可以让它更复杂一点

evens = [i for i in range(10) if i % 2 == 0]
>> [0, 2, 4, 5, 8]

这个问题与其说是如何让 Go 像 Python 一样工作,我想知道 Go 开发人员如何本机/自然地实现同样的事情。

标签: go

解决方案


[我]有没有更简单的方法可以在 Go 中实现这一目标?

基本上没有。

您可以使用范围简化您的 for 循环,但就是这样。经验法则:围棋没有魔法。


推荐阅读