Golang中,利用反射和interface就可以做到,不废话看代码
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 }
输出:
[a b c e f g]
[1 2 3 4 5 6 7 8]
而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)))
输出:
['e', 'g', 'b', 'c', 'a', 'f']
[1, 2, 3, 4, 5, 6, 7, 8]
有疑问加站长微信联系(非本文作者)