递推式构造列表(List Comprehension),例:
list = [x*2 for x in lm]
切片list[start: stop: step]
sort 和 sorted: sort会改变list(in-place),而sorted返回排序好的列表(return values),原有的不改变. 参数有sequen和key,key值代表按(...)进行排序。
list.sort()
sorted(list1)
sorted(dict, key=lambda x:dict[x])#按字典中的value进行排序
sorted(dict) #默认对字典的key进行排序
Warning:return values vs. in-place change
map(func, seq) #返回的是迭代器,可用for进行访问
list(map(func, seq)) #转换为list对象
如下先x1与x2进行func操作,再与x3func操作,再与x4func操作
reduce(func, [x1,x2,x3,x4])
对list的每个元素进行func操作,如果值为True,则保留。
filter(func, list)
------------------------------------------------------------------------------------------------
.pop(_)操作既return values,又in-place。
join:
delimeter = '*'
s = delimeter.join(t) #返回以delimeter连接t中元素的字符串
------------------------------------------------------------------------------------------------
直接赋值,引用复制,在内存中实际指向同一个对象。
>>> a = [1,2,3]
>>> b = a
>>> b is a
True
>>> b[0] = 100
>>> a
[100, 2, 3]
a切片赋值给b,b改变,a不会发生改变
>>> a = [1,2,3,4]
>>> b = a[:]
>>> b[0]= 100
>>> a
[1, 2, 3, 4]
>>> b
[100, 2, 3, 4]
deep copy(完全复制,不会互相影响)
>>> import copy
>>> a = [1,2,3,4]
>>> b = copy.deepcopy(a)
>>> b
[1, 2, 3, 4]
>>> b[0] = 100
>>> a
[1, 2, 3, 4]
>>> b
[100, 2, 3, 4]
>>> a[1] = 200
>>> b
[100, 2, 3, 4]
shallow copy:
>>> import copy
>>> a = [1,2,[1,2,3]]
>>> b = copy.copy(a)
>>> b
[1, 2, [1, 2, 3]]
>>> b[0] = 100
>>> a
[1, 2, [1, 2, 3]]
>>> a[1] = 200
>>> b
[100, 2, [1, 2, 3]]
>>> b[2] = 3
>>> b
[100, 2, 3]
>>> a
[1, 200, [1, 2, 3]]
dict is mapping 用空间换时间,适合作缓存
get
>>> a.get('age', 10)
18
>>> a = {'name': 'nn'}
>>> a.get('age', 10)
10
>>> a
{'name': 'nn'}
>>> b = {'name': 'nn', 'age': 18}
>>> b.get('age', 18)
18
>>> b
{'name': 'nn', 'age': 18}
setdefault()
缓存的概念
例:
known = {0:0, 1:1}
def fib(n):
if n in known:
return known[n]
res = fib(n-1) + fib(n-2)
known[n] = res
return res
packing and unpacking
zip
2018/5/4:上课笔记