欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Go基础编程实践(四)—— 数组和map

程序员文章站 2022-04-15 15:15:38
数组去重 查找元素 数组降序 迭代数组 将map转为数组 合并数组 合并map 判断map中key是否存在 ......

数组去重

package main

import "fmt"

func main(){
  intslice := []int{1,5,5,5,5,7,8,6,6, 6}
  fmt.println(intslice)
  uniqueintslice := unique(intslice)
  fmt.println(uniqueintslice)
}

func unique(intslice []int) []int{
  keys := make(map[int]bool)
  uniqueelements := []int{}
  for _,entry := range intslice {
    if _, value := keys[entry]; !value{
      keys[entry] =true
      uniqueelements = append(uniqueelements, entry)
    }
  }
  return uniqueelements
}

查找元素

package main

import (
  "fmt"
  "sort"
)

func main() {
  str := []string{"sandy", "provo", "st.george", "salt lake city", "draper", "south jordan", "murray"}

  // for循环查找
  for i, v := range str {
    if v == "sandy" {
      fmt.println(i)
    }
  }

  // sort包排序后查找
  // stringslice给[]string添加方法以满足interface接口,以便排序为递增序列。
  sortedlist := sort.stringslice(str)
  // 升序
  sortedlist.sort()
  fmt.println(sortedlist)
  index := sortedlist.search("sandy")
  fmt.println(index)
}

数组降序

package main

import (
  "sort"
  "fmt"
)

func main() {
  numbers := []int{1, 5, 3, 6, 2, 10, 8}
  // intslice给[]int添加方法以满足interface接口,以便排序为递增序列。
  tobesorted := sort.intslice(numbers)
  // reverse包装一个interface接口并返回一个新的interface接口,对该接口排序可生成递减序列。
  sort.sort(sort.reverse(tobesorted))
  fmt.println(tobesorted)
}

迭代数组

package main

import "fmt"

func main(){
  numbers := []int{1, 5, 3, 6, 2, 10, 8}

  for index,value := range numbers{
     fmt.printf("index: %v and value: %v\n", index, value)
  }
}

将map转为数组

package main

import "fmt"

type nameage struct{
  name string
  age int
}

func main(){
  var nameageslice []nameage
  nameages := map[string]int{
    "michael": 30,
    "john": 25,
    "jessica": 26,
    "ali": 18,
  }
  for key, value := range nameages{
    nameageslice = append(nameageslice, nameage {key, value})
  }

  fmt.println(nameageslice)

}

合并数组

package main

import "fmt"

func main(){
  items1 := []int{3,4}
  items2 := []int{1,2}
  result := append(items1, items2...)
  fmt.println(result)
}

合并map

package main

import "fmt"

func main(){
  map1 := map[string]int {
   "michael":10,
   "jessica":20,
   "tarik":33,
   "jon": 22,
  }
  fmt.println(map1)

  map2 := map[string]int {
    "lord":11,
    "of":22,
    "the":36,
    "rings": 23,
  }
  for key, value := range map2{
    map1[key] = value
  }
  fmt.println(map1)
}

判断map中key是否存在

package main

import "fmt"

func main() {
  nameages := map[string]int{
    "tarik": 32,
    "michael": 30,
    "jon": 25,
    "jessica" : 20,
  }
  if _, exists := nameages["jessica"]; exists{
    fmt.println("jessica can be found")
  }else {
    fmt.println("jessica cannot be found")
  }
}