等同于 Python 的列表理解

Equivalent for Python's list comprehension

我正在玩围棋,但我很难用其他语言做一些非常简单的事情。

我想复制一个 Python comprehension:

array = [a for a in anotherArray  if (some condition)]

在 Go 中有什么优雅的方法可以做到这一点?我真的很想简化我的代码,尤其是在数组上使用函数时。例如:

min = min(abs(a[i], b[j]) for i in range(n)
                          for j in range(i, n))

有趣的是,Rob Pike just proposed (18 hours ago) the library filter 可以满足您的需求:

for instance Choose()

// Choose takes a slice of type []T and a function of type func(T) bool. (If
// the input conditions are not satisfied, Choose panics.) It returns a newly
// allocated slice containing only those elements of the input slice that
// satisfy the function.

Tested here:

func TestChoose(t *testing.T) {
    a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
    expect := []int{2, 4, 6, 8}
    result := Choose(a, isEven)

twotwotwo points out , the GoDoc for this library 所述:

Package filter contains utility functions for filtering slices through the distributed application of a filter function.

The package is an experiment to see how easy it is to write such things in Go. It is easy, but for loops are just as easy and more efficient.

You should not use this package.

此警告反映在文档“Summary of Go Generics Discussions", section "Functional Code”中:

These are the usual higher-order functions such as map, reduce (fold), filter, zip etc.

Cases:
typesafe data transformations: map, fold, zip

Pros for using generics:
A concise way to express data transformations.

Cons for using generics:
The fastest solution needs to take into account when and in which order to apply those transformations, and how much data is generated at each step.
It is harder to read for beginners.

Alternative solutions:

use for loops and usual language constructs.


2022 年第一季度更新:在 Go 中首次集成泛型(例如参见“Tutorial: Getting started with generics"), you now have a possible mapreduce implementation with generics in Go.
参见 tip.playground, and the github.com/kevwan/mapreduce/v2 项目。

如果您正在寻找的确实是 python 列表理解,go AFAIK 中没有这样的句法等价物。

方法是创建一个函数,该函数接受一个切片和一个函数(用于测试条件)和 return 一个新切片。

编辑: 好吧,看起来 Go 中已经有这样的功能了。比照 VonC