等效于Python的列表理解 [英] Equivalent for Python's list comprehension

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

问题描述

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

I am playing with Go but I am having a very hard time doing things that are very simple in other languages.

我想重现类似的语法:

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

在Go中做这件事的一种优雅方法是什么?我真的想简化我的代码,尤其是在数组上使用函数时.例如:

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

非常感谢

推荐答案

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

Interestingly enough, Rob Pike just proposed (18 hours ago) the library filter which does a bit what you want:

请参见例如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.

在这里测试:

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 指出 GoDoc此库的状态:

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

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

该程序包是一项实验,旨在了解在Go中编写此类代码有多么容易.这很简单,但是 for循环既简单又有效..

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.

您不应使用此软件包.

此警告反映在文档" 摘要中泛型讨论" "部分," 功能代码 ":

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

这些是常用的高阶函数,例如map(fold),filterzip

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

案例:
类型安全的数据转换:mapfoldzip

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.

替代解决方案:

使用for循环和常用语言构造.

use for loops and usual language constructs.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆