Array
ArrayList 动态数组/数组列表
基础知识
- 顺序储存数据
- 连续储存
- 任意顺序访问,可变大小的列表数据结构允许增加、删除元素
抽象数据类型
- E.g., a list of available hotel rooms, a list of cities, and a list of books
- Data Abstraction
- Decide what data elements you will be operating on
- Decide what operations you will be doing to each data element
- Define a clean interface to these operations
- Implement the objects
- Now you have an Abstract Data Type (ADT)
Python Array vs. List
数组和动态数组的最大区别:
数组的大小是固定的,动态数组的大小是可以改变的!
Array Module - Sequence of fixed-type data
- python array
用来储存序列的数据,且其中的数据必须有相同的数据类型:要求是全部为数字或者其它固定大小的原始类型如字节。(除了需要相同的数据类型之外,与 list 几乎一样)
import array
import binascii
s = 'sample'
a = array.array('u', s)
print('As string:', s)
print('As array :', a)
As string: sample
As array : array('u', 'sample')
python string
- string
python 利用 string 来储存具有不同大小/长度的序列数据。
虽然初始元素的大小可能不同,但是用于存储每个元素的存储器地址的位的数目是固定的(每个地址例如,64位)
List 实例
-
切片操作
A single list instance may include multiple references to the same object as elements of the list, and it is possible for a single object to be an element of two or more lists, as those lists simply store references back to that object. As an example, when you compute a slice of a list, the result is a new list instance, but that new list has references to the same elements that are in the original list.
-
浅拷贝
# let's play some tricks
# array slicing: make a copy!!!
a = list(range(0, 9))
print(a)
b = a[3:7]
print(b)
b[0] = -1
print(a)
print(b)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[-1, 4, 5, 6]
import numpy as np
a = np.arange(10)
print(a)
b = a[3:7]
print(b)
b[0] = -1
print(a)
print(b)
b = a[3:7].copy()
print(b)
b[1] = -2
print(a)
print(b)
[0 1 2 3 4 5 6 7 8 9]
[3 4 5 6]
[ 0 1 2 -1 4 5 6 7 8 9]
[-1 4 5 6]
[-1 4 5 6]
[ 0 1 2 -1 4 5 6 7 8 9]
[-1 -2 5 6]
- 深拷贝
a = [0] * 8
a[2] = 1
a
[0, 0, 1, 0, 0, 0, 0, 0]
a = [[0] * 8] * 8
a[0][0] = 9
a
[[9, 0, 0, 0, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 0, 0, 0],
[9, 0, 0, 0, 0, 0, 0, 0]]
- 初始化二维的列表
To properly initialize a two-dimensional list, we must ensure that each cell of the primary list refers to an independent instance of a secondary list. This can be accomplished through the use of Python’s list comprehension syntax.
m, n = 3, 2
data = [ [0] * n for j in range(m) ]
data
[[0, 0], [0, 0], [0, 0]]
List
字符串是字符的序列,列表是对象的序列。当对象的顺序很重要时,我们使用 LIst。
- ADT List Operations
- Create an empty list
- Determine whether the list is empty
- Determine the number of items in a list
- Add an item at given position in a list
- Remove the item at a given position in a list
- Remove all the items from a list
- Get the item at a given position in a list
- Other operations?