Python实用技巧1/?

复习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)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值