如何在golang中实现python`zip`功能?

前端之家收集整理的这篇文章主要介绍了如何在golang中实现python`zip`功能?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有时,使用 Python中的zip内置函数将两个列表组合成一个元组很方便.在高隆怎么样呢?
你可以做一些类似 this的类,你给你的元组类型一个名字:
package main

import "fmt"

type intTuple struct {
    a,b int
}

func zip(a,b []int) ([]intTuple,error) {

    if len(a) != len(b) {
        return nil,fmt.Errorf("zip: arguments must be of same length")
    }

    r := make([]intTuple,len(a),len(a))

    for i,e := range a {
        r[i] = intTuple{e,b[i]}
    }

    return r,nil
}

func main() {
    a := []int{1,2,3,4,5,6,7,8,9,0}
    b := []int{0,1}
    fmt.Println(zip(a,b))
}

或者使用未命名的类型作为元组,如this

package main

import "fmt"

func zip(a,b []int) ([][3]int,fmt.Errorf("zip: arguments must be of same length")
    }

    r := make([][4]int,e := range a {
        r[i] = [2]int{e,b))
}

最后here’s是一种软通用的方式:

package main

import (
    "fmt"
    "reflect"
)

func zip(a,b,c interface{}) error {

    ta,tb,tc := reflect.TypeOf(a),reflect.TypeOf(b),reflect.TypeOf(c)

    if ta.Kind() != reflect.Slice || tb.Kind() != reflect.Slice || ta != tb {
        return fmt.Errorf("zip: first two arguments must be slices of the same type")
    }

    if tc.Kind() != reflect.Ptr {
        return fmt.Errorf("zip: third argument must be pointer to slice")
    }

    for tc.Kind() == reflect.Ptr {
        tc = tc.Elem()
    }

    if tc.Kind() != reflect.Slice {
        return fmt.Errorf("zip: third argument must be pointer to slice")
    }

    eta,_,etc := ta.Elem(),tb.Elem(),tc.Elem()

    if etc.Kind() != reflect.Array || etc.Len() != 2 {
        return fmt.Errorf("zip: third argument's elements must be an array of length 2")
    }

    if etc.Elem() != eta {
        return fmt.Errorf("zip: third argument's elements must be an array of elements of the same type that the first two arguments are slices of")
    }

    va,vb,vc := reflect.ValueOf(a),reflect.ValueOf(b),reflect.ValueOf(c)

    for vc.Kind() == reflect.Ptr {
        vc = vc.Elem()
    }

    if va.Len() != vb.Len() {
        return fmt.Errorf("zip: first two arguments must have same length")
    }

    for i := 0; i < va.Len(); i++ {
        ea,eb := va.Index(i),vb.Index(i)
        tt := reflect.New(etc).Elem()
        tt.Index(0).Set(ea)
        tt.Index(1).Set(eb)
        vc.Set(reflect.Append(vc,tt))
    }

    return nil
}

func main() {

    a := []int{1,1}
    c := [][2]int{}

    e := zip(a,&c)

    if e != nil {
        fmt.Println(e)
        return
    }

    fmt.Println(c)
}
原文链接:https://www.f2er.com/go/186797.html

猜你在找的Go相关文章