python_list 插入 追加 合并 拷贝 copy 排序

1
2
3
4
5
6
7
8
9
10
array = [1, 2, 5, 3, 6, 8, 4]
array[0:]
array[1:] #列出1以后的 [2, 5, 3, 6, 8, 4]
array[:-1] #列出-1之前的 [1, 2, 5, 3, 6, 8]
array[::2] # [1, 5, 6, 4]
array[2::] # [5, 3, 6, 8, 4]
array[::3] # [1, 3, 4]
array[::4] # [1, 6]
array[::-1] # [4, 8, 6, 3, 5, 2, 1]
array[::-2] # [4, 6, 5, 1]

插入

1
2
3
list.insert(index, obj)

ret.insert(0, code['symbol'])

追加

1
2
3
4
list = []          ## 空列表
list.append('Google') ## 使用 append() 添加元素
list.append('Runoob')
print list

合并

1
datas.extend(aa)

拷贝 copy

只有 copy.deepcopy 能拷贝嵌套数组的列表

默认是引用传值的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import copy
a = [[10], 20]
b = a[:]
c = list(a)
d = a * 1
>>> e = copy.copy(a)
>>> f = copy.deepcopy(a)
>>> a.append(21)
>>> a[0].append(11)
>>> print id(a), a
[[10, 11], 20, 21]
>>> print id(b), b
[[10, 11], 20]
>>> print id(c), c
[[10, 11], 20]
>>> print id(d), d
[[10, 11], 20]
>>> print id(e), e
[[10, 11], 20]
>>> print id(f), f
[[10], 20]

排序

1
2
from operator import itemgetter
picked_sorted = sorted(picked, key=itemgetter(3))