1. list
1.1 reverse a list
- slicing
lst[::-1]
有返回值,返回一個新的list,原list不變
注:slicing操作都是返回一個新的list
- reverse( )
lst.reverse( )
返回None,原list翻轉(zhuǎn)
- reversed()
list(reversed(lst))
返回一個新的list,原list不變
reversed( ) return a "reverse iterator"
1.2 list method
- append( ) & extend( )
append( ) 在list后邊添加一個值
extend( ) 在list后面添加給定的所有值,參數(shù)為list或者tuple (其他seq應(yīng)該也可以)
>>> lst = [1,2]
>>> lst.extend([3,4])
>>> lst
[1, 2, 3, 4]
>>> lst.extend((5,6))
>>> lst
[1, 2, 3, 4, 5, 6]
- remove(x) & pop([i]) & del
remove(x)刪除從左邊第一個出現(xiàn)的值為x的元素,如果沒有match的元素,返回error
pop( )默認(rèn)彈出最后一個元素,也可以指定彈出的index
del好像并不是list的方法
del( )刪除指定index的元素,或者一個slice段
del( )無返回值,pop( )會返回彈出的元素 - index(x)
- count(x)
- sort(cmp=None, key=None, reverse=False)
1.3 stack & queue
stack
直接用append( )和pop( )即可queue
however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
list不適合用來做queue
如果要用queue的話,參考deque
from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry")
>>> queue.append("Graham")
>>> queue.popleft()
'Eric'
>>> queue.popleft()
'John'
1.4 Functional Programming Tools
filter(function, sequence):
給定一個序列,返回sequence中滿足function條件為true的序列map(function, sequence):
對于sequence中的每個元素,調(diào)用function函數(shù),然后返回值組成一個list
>>> seq = range(8)
>>> def add(x, y): return x+y ...
>>> map(add, seq, seq)
[0, 2, 4, 6, 8, 10, 12, 14]
- reduce(function, sequence):
每次sequence中的前兩個元素作為參數(shù)調(diào)用function,返回的結(jié)果與后面一個元素繼續(xù)調(diào)用function,知道sequence結(jié)束
>>> def add(x,y): return x+y
...
>>> reduce(add, range(1, 11))
55
2 其他類型
2.1 tuple
- tuple不能修改
- empty tuple: empty = ( )
- tuple with 1 element: single = 13,
在末尾加一個逗號
2.2 set
- set是無序的(unordered)
- 創(chuàng)建set,用set( )或者{ },{ }不能用來創(chuàng)建空set,{ }會創(chuàng)建一個空的字典
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) # create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
- set可以做集合運算
-, |, &, ^
2.3 dictionary
- dictionary的key必須是不可修改的類型,通常為number或者string,tuple也可以 (tuple中不能包含可修改類型,如list)
操作符
- / 和 //
如果兩個操作數(shù)都是int,/ 返回類型int,執(zhí)行floor division
如果任何一個操作數(shù)是float,/ 返回類型float,執(zhí)行正常除法
// 無論如何都返回floor division,但類型仍然是浮點數(shù)
>>> 3.0 // 2
1.0
floor division: Mathematical division that rounds down to nearest integer.
Strings
' 和 ‘’ 功能一樣
""' 或者 ‘’‘ 用來處理跨行字符串r 代表原始字符串,不轉(zhuǎn)義
>>> print r'C:\some\name'
C:\some\name
在regex時候也常用到
- string不能修改
shallow copy & deep copy
to be continued
lambda表達(dá)式
to be continued
賦值順序
a, b = b, a+b
the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.
循環(huán)
循環(huán)中使用else
例子:search for prime numbers
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
print n, 'is prime number'
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
循環(huán)技巧
- index和value一起循環(huán)
for i, v in enumerate(['a', 'b', 'c']):
print i, v
- 循環(huán)dictionary的key和value,用iteritems()
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
參數(shù)
- 收集參數(shù)
def cheeseshop(kind, *arguments, **keywords):
print kind
for arg in arguments:
print arg
keys = sort(keywords.keys())
for key in keys:
print keywords[key]
* : 收集其余位置的參數(shù),如果不提供任何收集的元素,則為空元組,收集的參數(shù)存儲在tuple中
** : 收集帶有關(guān)鍵字的參數(shù),存儲在dict中
- unpacking argument list
def parrot(voltage, state='a stiff', action='voom'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "volts through it.",
print "E's", state, "!"
#
d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)