Golang、python去除slice和list的重複元素,很是有用的功能

Golang中,利用反射和interface就能夠作到,不廢話看代碼python

func main() {
  b := []string{"a", "b", "c", "c", "e", "f", "a", "g", "b", "b", "c"}
   sort.Strings(b)
   fmt.Println(Duplicate(b))
   

   c := []int{1, 1, 2, 4, 6, 7, 8, 4, 3, 2, 5, 6, 6, 8}
   sort.Ints(c)
   fmt.Println(Duplicate(c))
}
func Duplicate(a interface{}) (ret []interface{}) {
   va := reflect.ValueOf(a)
   for i := 0; i < va.Len(); i++ {
      if i > 0 && reflect.DeepEqual(va.Index(i-1).Interface(), va.Index(i).Interface()) {
         continue
      }
      ret = append(ret, va.Index(i).Interface())
   }
   return ret
}

輸出:app

[a b c e f g]函數

[1 2 3 4 5 6 7 8]string

 

而python自帶的系統函數就能作到反射

a=["a", "b", "c", "c", "e", "f", "a", "g", "b", "b", "c"]
print(list(set(a)))


a=[1, 1, 2, 4, 6, 7, 8, 4, 3, 2, 5, 6, 6, 8]
print(list(set(a)))

輸出:sort

['e', 'g', 'b', 'c', 'a', 'f']
[1, 2, 3, 4, 5, 6, 7, 8]co

相關文章
相關標籤/搜索