Golang相当于Python的列表理解 [英] Golang equivalent for Python's list comprehension
问题描述
我正在玩Go,但我很难用其他语言做很简单的事情。
我想重现类似的语法:
array = [a for a anotherArray if(some condition)]
在Go中执行该操作的优雅方法是什么?我真的很想简化我的代码,特别是在数组上使用函数时。例如:对于范围(n)中的i,
min = min(abs(a [i],b [j]
for j in range(i,n))
非常感谢
有趣的是, Rob Pike 刚刚提出(18小时前)图书馆过滤器,它有点你想要的:
请参阅实例选择()
//选择一个类型为[] T的类型和一个类型为func的函数( T)布尔。 (如果
//输入条件不满足,请选择panics。)它将返回一个新的
//分配的片,其中只包含
//满足函数的输入片元素。 b
$ b apply_test.go#L67-L70rel =nofollow noreferrer>在此测试:
$ b
func TestChoose(t * testing.T){
a:= [] int {1,2,3,4,5,6,7,8,9}
expect:= [] int {2,4,6 ,8}
结果:=选择(a,isEven)
As twotwotwo
指出在评论中,
包过滤器
包含实用功能,用于通过过滤器功能的分布式应用程序来过滤切片。
该软件包是一个实验,用于查看ea sy就是在Go里写这些东西。这很容易,但 for
循环同样简单且高效。
您不应该使用这个包。
这个警告反映在文档 Go Generics讨论摘要 ,section 功能代码 :
这些通常是高级函数,比如 map
, reduce
( fold
),过滤器, zip
等。
案例:
类型安全数据转换: map
, fold
, zip
使用泛型的优点:
简明的表达数据转换的方式。
使用泛型的缺点:
最快的解决方案需要考虑何时,以何种顺序应用这些转换,以及在每个步骤中生成多少数据。
这对初学者来说很难阅读。
替代解决方案:
<使用作为
循环和常用语言结构。
I am playing with Go but I am having a very hard time doing things that are very simple in other languages.
I'd like to reproduce a similar syntax:
array = [a for a in anotherArray if (some condition)]
What is an elegant way to do it in Go? I'd really like to simplify my code especially when using function on array. For example:
min = min(abs(a[i], b[j]) for i in range(n)
for j in range(i, n))
Many thanks
解决方案 Interestingly enough, Rob Pike just proposed (18 hours ago) the library filter which does a bit what you want:
// 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.
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)
As twotwotwo
points out in the comments, the GoDoc for this library states:
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.
This caveat is reflected in the document "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:
Concise way to express data transformations.
Cons for using generics:
The fastest solution needs to take into account when and 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.
这篇关于Golang相当于Python的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!