Uniqify
The Python version is neat in that it's entirely type agnostic as long asthe value supports hashing.I'm sure it's possible to do an equivalent one in Go using interface{}
.Patches welcome.
For faster variants in Python seeFastest way to uniqify a list inPython.
For some more thoughts on this, and an example of a implementationthat is not in-place check out this mailing listthread.
Python
- 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']
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]
- }