gpt4 book ai didi

python - 等效于 Python 的列表推导

转载 作者:IT老高 更新时间:2023-10-28 13:02:46 25 4
gpt4 key购买 nike

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

我想复制 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刚刚提议(18 小时前)图书馆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指出 in the comments , 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.

此警告反射(reflect)在文档“Summary of Go Generics Discussions”的“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”),您现在有可能的 mapreduce implementation with generics in Go .
tip.playground ,以及 github.com/kevwan/mapreduce/v2项目。

关于python - 等效于 Python 的列表推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27848406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com