[python]20131113

#Data Structures List的控制

x=value i=index position L=list

  • list.append(x) : 在結尾的地方新增一筆資料
  • list.extend(L) : 新增資料by list
  • list.insert(i,x) : 插入資料
  • list.remove(x) : 移除所輸入的x值
  • list.pop([i]) : 移除所指定index position的值;如果沒有指定[i]時,則傳回並移除最後一筆紀錄(後進先出)
  • list.clear() : 清除list
  • list.index(x) : x值的位置, 如果沒有找到則傳回錯誤
  • list.count(x) : x值的數量
  • list.sort() : 排序
  • list.reverse() : 反轉
  • list.copy() : 複製list

後進先出 : list.pop() 先進先出 : deque deque([list])後,在操作pop或append時,多出了popleft(), appendleft(), extendleft()的方法 用法如下

1
2
3
4
5
6
7
8
9
10
11
12
>>>from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue
deque(['Eric', 'John', 'Michael'])
>>> queue.append("Kevin")
deque(['Eric', 'John', 'Michael', 'Kevin'])
>>> queue.appendleft("Steve")
deque(['Steve', 'Eric', 'John', 'Michael', 'Kevin'])
>>> queue.popleft()
'Steve'
>>> queue
deque(['Eric', 'John', 'Michael', 'Kevin'])

#List Comprehensions ##(計算x) for x in list if condition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

>>> [x**2 for x in range(10) if x%2==0]
[0, 4, 16, 36, 64]

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

#del 移除list中的值by Index

1
2
3
4
5
6
7
8
9
10
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

del can also be used to delete entire variables: 變數消滅

1
2
3
4
5
6
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined