1. list
1.1 reverse a list
- slicing
lst[::-1]
有返回值,返回一个新的list,原list不变
注:slicing操作都是返回一个新的list
- reverse( )
lst.reverse( )
返回None,原list翻转
- reversed()
list(reversed(lst))
返回一个新的list,原list不变
reversed( ) return a "reverse iterator"
1.2 list method
- append( ) & extend( )
append( ) 在list后边添加一个值
extend( ) 在list后面添加给定的所有值,参数为list或者tuple (其他seq应该也可以)
>>> 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)删除从左边第一个出现的值为x的元素,如果没有match的元素,返回error
pop( )默认弹出最后一个元素,也可以指定弹出的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中的每个元素,调用function函数,然后返回值组成一个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中的前两个元素作为参数调用function,返回的结果与后面一个元素继续调用function,知道sequence结束
>>> 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)
- 创建set,用set( )或者{ },{ }不能用来创建空set,{ }会创建一个空的字典
>>> 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)
操作符
- / 和 //
如果两个操作数都是int,/ 返回类型int,执行floor division
如果任何一个操作数是float,/ 返回类型float,执行正常除法
// 无论如何都返回floor division,但类型仍然是浮点数
>>> 3.0 // 2
1.0
floor division: Mathematical division that rounds down to nearest integer.
Strings
' 和 ‘’ 功能一样
""' 或者 ‘’‘ 用来处理跨行字符串r 代表原始字符串,不转义
>>> print r'C:\some\name'
C:\some\name
在regex时候也常用到
- string不能修改
shallow copy & deep copy
to be continued
lambda表达式
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.
循环
循环中使用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.
循环技巧
- index和value一起循环
for i, v in enumerate(['a', 'b', 'c']):
print i, v
- 循环dictionary的key和value,用iteritems()
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
参数
- 收集参数
def cheeseshop(kind, *arguments, **keywords):
print kind
for arg in arguments:
print arg
keys = sort(keywords.keys())
for key in keys:
print keywords[key]
* : 收集其余位置的参数,如果不提供任何收集的元素,则为空元组,收集的参数存储在tuple中
** : 收集带有关键字的参数,存储在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)