Data Structures
數(shù)值Numbers
簡單的數(shù)值計算,計算器功能
運(yùn)算符
+ - * /
// #保留整數(shù)部分
% #取余數(shù)
** #power
字符串Strings
- 單引號和雙引號馍资,不沖突原則
- 單引號中
\n
在print
時要換行,使用r
前綴避免解釋轉(zhuǎn)意字符 -
+
,*
操作
3 * 'un' + 'ium'
=>unununium
'Py' 'thon'
=>Python
#這種操作只能簡單連接员凝,不能復(fù)合操作('un' * 3) 'ium'
- Strings can be indexed (subscripted)
word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'
- 能索引就意味著能切片
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'
- 看一看索引號,可以這樣認(rèn)為:正索引從0開始左閉右開响鹃,負(fù)索引從-1開始全閉
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
- 不可通過索引改變string的元素,Python strings cannot be changed — they are immutable
-
len()
returns the length of a string
列表Lists
- 通過
[]
定義列表squares = [1, 4, 9, 16, 25]
- 和String一樣List也是內(nèi)置的sequence類型所以能夠使用同樣的索引和切片方法
- Lists也支持合并
+
操作 - Lists是mutable的乎串,
- 使用賦值
=
操作來改變元素值cubes[3] = 64
或者letters[2:5] = ['C', 'D', 'E']
- 在末尾加入新項
cubes.append(216)
- 同樣可以使用
len()
返回長度 - 支持嵌套使用店枣,It is possible to nest lists (create lists containing other lists)。
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
- 下面總結(jié)一下Lists的操作方法
list.append(x)**:末尾增一項叹誉,這一項可以是各種對象鸯两。Add an item to the end of the list; equivalent to
a[len(a):] = [x]
list.extend(L)**:先展開所增對象,然后在末尾一一增項长豁,Extend the list by appending all the items in the given list; equivalent to
a[len(a):] = L
list.insert(i, x)**:在i位置插入一項x钧唐。Insert an item at a given position. The first argument is the index of the element before which to insert, so
a.insert(0, x)
inserts at the front of the list, anda.insert(len(a), x)
is equivalent toa.append(x)
list.remove(x)**:刪除值為x的索引值最小項。Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i])**:刪除并返回給定位置i的項蕉斜,如果使用pop()則是刪除最后一項并返回其值逾柿。Remove the item at the given position in the list, and return it. If no index is specified, a.pop()removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
list.index(x)**:返回值為x的第一項索引號。Return the index in the list of the first item whose value is x. It is an error if there is no such item.
list.count(x)**:返回x出現(xiàn)的次數(shù)宅此。Return the number of times x appears in the list.
list.sort(cmp=None, key=None, reverse=False)**: 排序机错。Sort the items of the list in place (the arguments can be used for sort customization.
list.reverse():倒轉(zhuǎn)Lists。Reverse the elements of the list, in place.
- 通過上面方法的總結(jié)父腕,通常以如下幾種方式使用List
- Using Lists as Stacks (“l(fā)ast-in, first-out”):
append
andpop
method, - Using Lists as Queues (“first-in, first-out”): using collections.deque
from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves'Eric'
>>> queue.popleft() # The second to arrive now leaves'John'
>>> queue # Remaining queue in order of arrivaldeque(['Michael', 'Terry', 'Graham'])
Functional Programming Tools: 函數(shù)式編程工具
有三個內(nèi)置函數(shù)在Lists的使用上非常方便:
-
filer(function, sequence)
: 返回一個sequence弱匪,返回序列對原序列的篩選,篩選方法是function。返回的序列與原序列類型相同萧诫,可以使用這個方法篩選數(shù)據(jù)斥难。這里作為參數(shù)的function定義有一定要求,fucntion要有一個參數(shù)帘饶,并且其返回值只能是0或1,所以這個函數(shù)邏輯性的過濾函數(shù)
>>> def f(x): return x % 3 == 0 or x % 5 == 0
...
>>> filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
-
map(function,sequence,seq...)
: 返回一個sequence哑诊,返回序列各個項是function作用到原序列各個項獲得的結(jié)果。這里的作用函數(shù)特點(diǎn)是及刻,參數(shù)個數(shù)要與map的序列個數(shù)一致镀裤,并且各個序列的長度要一致。function返回與這些參數(shù)相關(guān)的值缴饭。這是一個典型的映射操作(map)暑劝。
- 單序列映射
>>> def cube(x): return x*x*x
...
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
- 多序列映射
def func2(x,y,z): return x+y*z
a = range(7); b = range(7,14)
dd = map(func2,a,b,a)
//result:[0, 9, 20, 33, 48, 65, 84]
map()的原理可以用下圖表示:
-
reduce(function,seq)
: reduce把一個函數(shù)作用在一個序列[x1, x2, x3...]
上,這個函數(shù)必須接收兩個參數(shù)颗搂,reduce把結(jié)果繼續(xù)和序列的下一個元素做累積計算担猛,其效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
。注意丢氢,funciton的參數(shù)只能有兩個傅联。
這里列舉幾個例子體會一下reduce()
的使用:
- 求和
>>> def add(x, y)
:... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
- 把序列
[1, 3, 5, 7, 9]
變換成整數(shù)13579
def func3(x,y):
return 10*x+y
ff = reduce(func3,[0,1,2,3,4])
print(ff)
#result: 1234
- 把
str
轉(zhuǎn)換為int
def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def str2int(s): return reduce(lambda x,y: x*10+y, map(char2num, s))
List Comprehensions列表生成式
- range
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- for...in...
>>> L = []
>>> for x in range(1, 11):
... L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
- 列表生成式(一層循環(huán))
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
當(dāng)然,還可以用lambda
&map
來寫
map(lambda x: x*x, range(1,11))
但是卖丸,這樣表達(dá)沒有列表生成器簡明易讀(it’s more concise and readable)
- 列表生成式(兩層循環(huán)),所得列表長度等于循環(huán)次數(shù)
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
- 列表生成器(增加
if
判斷)
>>> [(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)]
Tuples and Sequences 元組和序列
A tuple consists of a number of values separated by commas. tuple通常用
()
表示纺且,tuple屬于immutable類型的序列,不支持賦值操作稍浆,但是它可以嵌套mutable的list類型( however it is possible to create tuples which contain mutable objects, such as lists.).
- tuple packing:
t = 12345, 54321, 'hello!'
- tuple unpacking:
x,y,z = t
- tuple元素為異構(gòu)的载碌,通過unpack或index方式訪問;sequence元素為同構(gòu)的衅枫,通過iterator方式訪問
- 兩種特殊的tuple
# tuple with zero or one element
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> singleton
('hello',)
- tuple packing and unpacking
t = 12345, 54321, 'hello!' # packing
x, y, z = t # unpacking
- 遍歷list, 按索引值和value值顯示, enumerate
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
- 同時遍歷兩個list,
zip
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
Sets 集合
A set is an unordered collection with no duplicate elements.Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.Note: to create an empty set you have to use
set()
, not{}
,創(chuàng)建空set要使用set()
不能用{}
- 由
list
生成set
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
- 由
string
生存set
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
- 集合操作
-
a - b
: 差集 in a but not in b -
a | b
: 或集 in either a or b -
a & b
: 并集 in both a and b -
a ^ b
:(a | b) - (a & b)
in a or b but not both
-
- set comprehensions集合生成器
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
set(['r', 'd'])
- 添加與刪除方法
- add(key)
- remove(key)
Dictionaries字典
- 刪除一個元素,
del(dic)
- 列出所有的key,
list(dic)
- 按value排序key,
sorted(dic)
- 判斷key是否存在,
key in dic
- 遍歷字典
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)