如何使用go获取切片中的单个项目计数?

For example, this is a slice:

[1, 2, 3, 3, 4]

want to get single data 1, 2, 4 's count and return count = 3.

Maybe remove duplicate items(include itself) is an idea, but didn't find suitalbe method.


What I tried:

  func removeDuplicateItems() {
      intSlice := []int{1, 2, 3, 3, 4}
      fmt.Println(intSlice)

      keys := make(map[int]bool)
      list := []int{}
      for _, entry := range intSlice {
          if _, value := keys[entry]; !value {
              keys[entry] = true
              list = append(list, entry)
          }
      }

      fmt.Println(list)
  }

Got

[1 2 3 3 4]
[1 2 3 4]

I just changed your function a little bit:

func removeDuplicateItems() {
    intSlice := []int{1, 2, 3, 3, 4}
    fmt.Println(intSlice)

    keys := make(map[int]int)
    list := []int{}
    for _, entry := range intSlice {
        keys[entry]++
    }
    for k, v := range keys {
        if v == 1 {
            list = append(list, k)
        }
    }

    fmt.Println(list)
}

https://play.golang.org/p/ESFLhC4VC-l

At this point the list is not sorted. If you want to sort your list afterward you need to use the sortpackage.

I suppose a really easy & quick way to get the count of unique values would be to use a map:

data := map[int]bool{}
cnt := 0 // count of unique values
for _, i := range intSlice {
    if dup, ok := data[i]; !ok {
        // we haven't seen value i before, assume it's unique
        data[i] = false // add to map, mark as non-duplicate
        cnt++ // increment unique count
    } else if !dup {
        // we have seen value i before, but this is only the second time
        cnt-- // unique count goes down here
        data[i] = true // mark this value as known duplicate
    }
}

At the end of this loop, you'll have cnt with the count of unique values, and you can iterate the map data for all keys with value false to get the unique values that you found in the slice. All keys combined basically are the values in the slice, de-duplicated.