Golang相当于Python的列表理解

Spe*_*her 23 python go

我正在玩Go,但我很难做其他语言非常简单的事情.

我想重现一个类似的语法:

array = [a for a in anotherArray  if (some condition)]
Run Code Online (Sandbox Code Playgroud)

Go的优雅方式是什么?我真的很想简化我的代码,尤其是在使用数组上的函数时.例如:

min = min(abs(a[i], b[j]) for i in range(n)
                          for j in range(i, n))
Run Code Online (Sandbox Code Playgroud)

非常感谢

Von*_*onC 11

有趣的是,Rob Pike刚刚提出(18小时前)库过滤器,它可以满足您的需求:

参见例如选择()

// 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.
Run Code Online (Sandbox Code Playgroud)

在这里测试:

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)
Run Code Online (Sandbox Code Playgroud)

正如评论中twotwotwo指出的那样,该库GoDoc指出:

包中filter包含实用程序函数,用于通过过滤函数的分布式应用程序过滤切片.

该软件包是一个实验,看看在Go中编写这样的东西是多么容易.它很简单,但for循环同样简单,高效.

你不应该使用这个包.

这个警告反映在文档" Go Generics Discussions "中," 功能代码 "部分:

这些是通常的高阶函数map,reduce(fold), filter,zip等等

案例:
类型安全的数据转换:map,fold,zip

使用泛型的优点:
表达数据转换的简洁方法.

使用泛型的缺点:
最快的解决方案需要考虑应用这些转换的时间和顺序,以及每个步骤生成的数据量.
初学者更难阅读.

替代方案:

使用for循环和通常的语言结构.

  • 请注意突出的"你不应该使用这个包." 在http://godoc.org/robpike.io/filter (8认同)