复习SICP,准备考试,总结几个Python的小技巧吧。
Slicing
形式:[下限:上限:步长] (下限 ≤ index<上限,index∈[-len, len),其中index = -i 表示倒数第 i 个元素),返回一个新的list
三个参数均可省略,默认为[0:len:1]
>>> a = [0, 1, 2, 3, 4, 5]
>>> a[:]
[0, 1, 2, 3, 4, 5]
>>> a[::2]
[0, 2, 4]
>>> a[1:4:1]
[1, 2, 3]
>>> a[1:4:2]
[1, 3]
Map
形式:map(func, list1, list2...) func为带有k个参数的函数,共有k个list并对所有len取min,多余元素忽略,在Python3中返回一个iterator
>>> a = map(lambda x: x, [1, 2])
>>> next(a)
1
>>> a = map(lambda x, y: x + y, [1, 2], [3, 4])
>>> next(a)
3
Reduce
形式:reduce(func, list, init),func为带有两个参数的函数,init为初始值且可以省略
>>> def add(x, y):
return x + y
>>> reduce(add, [1, 2, 3])
6
>>> reduce(add, [1, 2, 3], 3)
9
Filter
形式:filter(func, list),func为一个返回值为True or False的函数,可以过滤掉不满足func(list[i]) == True的元素,Python3中返回一个iterator
>>> a = filter(lambda x: x % 2, [2, 3, 4])
>>> next(a)
3
Range
用法:range(l, r, 步长),~ [l ,r),返回类型为range
>>> list(range(1, 10, 2))
[1, 3, 5, 7, 9]
List Comprehensions
用法:[func(k) for k in s if condition],s为k的所有取值集合(list,range,tuple等),if语句可以省略
>>> numbers = range(5)
>>> my_list = [number * 2 for number in numbers]
>>> my_list
[0, 2, 4, 6, 8]
>>> my list = [number * 2 for number in numbers if number % 2]
>>> my_list
[2, 6]
Zip
用法:zip(list1, list2, list3...),对所有list的len取min,忽略多余的元素,Python3中返回一个iterator
>>> a = [1, 2, 3]
>>> b = [2, 3, 4]
>>> c = [3, 4, 5]
>>> next(zip(a, b))
(1, 2)
>>> next(zip(a, b, c))
(1, 2, 3)