工具使用篇——python中容易忽略的小点

1、reduce的用法

python2.7中可以直接作为内置函数引用,但是再python3中需要从functools里面导入:
描述:
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
eg:

from functools import reduce
reduce(lambda x,y:x*y,[1,2,3,4])
#输出为24即((1*2)*3)*4

!如果只包含一个元素哪?

from functools import reduce
reduce(lambda x,y:x*y,[4])
#输出?

感兴趣的自己试一下,答案是4,关于该输出的解释如下:

def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
    """
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
    """
    pass

大意如下:该函数,一直讲sequence的长度迭代到1时进行输出。所以如果输出的列表长度为1当然直接输出该结果。(大胆猜测,该方法的实现用的应该是递推无疑了)

2、zip

性能上的提升倒是不大,只是看着好舒服,对吧?

#对于同纬度的连个列表的遍历一般情况下是这样写的
for i in range(len(list1)):
	print(list1[i],list2[i])
#运用zip可以方便的这样写
for i,j zip(list1,list2):
	print(i,j)

3、enumerate

##对一个列表进行打印索引及值
for index,value in enumerate([1,2,3,4,5]):
    print(index,value)
    
0 1
1 2
2 3
3 4
4 5
###最爱的方法还是这一个
min(enumerate([1,2,3,4,5]))
Out[8]: (0, 1)
###直接获得最小值及下标

4、arange

介于range()只能生成整数节点和间隔的迭代器,使用numpy中的arange在画图等操作中生成任意间隔的等差数列可谓方便。

numpy.arange(0,3.4,0.1)
Out[10]: 
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2,
       1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5,
       2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3])
       

5、np.cumsum()

对数列的累加求和,特别是在求累计概率曲线的时候,比较好用。

np.cumsum([1,2,3,4])
Out[18]: array([ 1,  3,  6, 10], dtype=int32)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值