Go 中的 Python 列表理解等效
Python 的列表理解提供了一種簡潔的方法來過濾和轉換序列。在Go中,可以使用濾波函數來實現類似的功能。然而,for 循環可能提供更有效率、更直接的方法。
要重現Python 列表理解:
array = [a for a in anotherArray if (some condition)]
在Go 中,您可以使用以下過濾函數:
import ( "fmt" "math" "math/big" ) func main() { anotherArray := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} newArray := filter(anotherArray, func(a int) bool { return a%2 == 0 }) fmt.Println(newArray) // [2 4 6 8] }
過濾器函數有兩個參數:要過濾的序列和決定要包含哪些元素的謂詞函數。它傳回一個僅包含滿足謂詞的元素的切片。
對於更複雜的表達式,您可以使用 lambda 函數,類似於 Python 範例:
min := func() *big.Int { a := big.NewInt(0) return a }() for i := 0; i < n; i++ { for j := i; j < n; j++ { potentialMin := big.NewInt(0) potentialMin.Abs(a[i].Sub(a[i], b[j])) if potentialMin.Cmp(min) == -1 { min = potentialMin } } }
但是,GoDoc過濾器庫建議 for 迴圈比套件更有效且更可取。因此,為了簡單性和可讀性,建議使用 for 迴圈。
以上是如何在Go中實現Python列表理解功能?的詳細內容。更多資訊請關注PHP中文網其他相關文章!