5. Lists-切片¶
切片是数组的一部分,其长度可以更改。
数组和切片之间的主要区别在于,使用数组需要预先知道大小。在Go中,无法平等地将值添加到现有切片中,因此,如果要轻松添加值,则可以以最大长度初始化切片并将其增量添加。
5.1. Python¶
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2020/4/21 13:50
# filename: sample1.py
# initialize list
numbers = [0] * 5
# change one of them
numbers[2] = 100
some_numbers = numbers[1:3]
print(some_numbers) # [0, 100]
# length of it
print(len(numbers)) # 5
# initialize another
scores = []
scores.append(1.1)
scores[0] = 2.2
print(scores) # [2.2]
5.2. Go¶
package main
import "fmt"
func main() {
// initialized array
var numbers [5] int // becomes [0, 0, 0, 0, 0]
// change one of them
numbers[2] = 100
// create a new slice from an array
some_numbers := numbers[1:3]
fmt.Println(some_numbers) // [0, 100]
// length of it
fmt.Println(len(some_numbers)) //2
// initialize a slice
var scores []float64
scores = append(scores, 1.1) // recreate to append
scores[0] = 2.2 // change your mind
fmt.Println(scores) // prints [2.2]
// when you don't know for sure how much you're going
// to put in it, one way is to
var things [100]string
things[0] = "Perter"
things[1] = "hujianli"
fmt.Println(len(things)) //100
}