本文介绍了Golang相当于Python的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩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))

非常感谢

解决方案

有趣的是,,它有点你想要的:



请参阅

  //选择一个类型为[] 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 指出中,,section :


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:

See 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)

As twotwotwo points out in the comments, the GoDoc for this library states:

This caveat is reflected in the document "Summary of Go Generics Discussions", section "Functional Code":

这篇关于Golang相当于Python的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:34