23. Uniqify(去重)

23.1. Python

#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2020/4/21 13:50
# filename: sample1.py

def uniqify(seq):
    seen = {}
    unique = []
    # 遍历序列,如果不在字典中,先加入字典,加入列表,在字典中的为重复的,不加入列表
    for item in seq:
        if item not in seen:
            seen[item] = 1
            unique.append(item)
    return unique


items = ['B', 'B', 'E', 'Q', 'Q', 'Q']
print(uniqify(items))  # prints ['B', 'E', 'Q']

23.2. Go

package main

import "fmt"

func uniqify(items *[]string) {
    seen := make(map[string]bool)
    j := 0
    for i, x := range *items {
        if !seen[x] {
            seen[x] = true
            (*items)[j] = (*items)[i]
            j++
        }
    }
    *items = (*items)[:j]
}

func main() {
    items := []string{"B", "B", "E", "Q", "Q", "Q"}
    uniqify(&items)
    fmt.Println(items) // prints [B E Q]
}