python 常见函数_Python 10个常用函数

round函数

# 四舍五入保留小数后两位

IN[0]: round(3.146,2)

OUT[0]: 3.15

floor函数

import math

# 向下取整

IN[1]: math.floor(3.14)

OUT[1]: 3

ceil函数

# 向上取整

IN[2]: math.ceil(3.14)

OUT[2]: 4

range函数

# 生成序列

In[3]: list(range(10,1,-2))

Out[3]: [10,8,6,4,2]

max/min函数

# key 函数定制比较规则,返回出现最高频元素

IN[4]: a=[1,3,3,2,3,1]

IN[5]: max(a,key=lambda,x:a.count(x))

Out[5]: 3

all 和 any函数

# all所有元素都为True返回True,否则返回False

IN[6]: all([True,True,False,True])

Out[6]: False

# any只要一个元素为True,返回True

IN[7]: any([False,True,False,True])

Out[7]: True

sorted函数

# 查找前,一般都会用到排序操作

# 按照元素频次排序

IN[8]: a=[1,3,3,2,3,1,3]

IN[9]: sorted(a.key=lambda x:acount(x),reverse=True)

Out[9]:[3,3,3,3,1,1,2]

sum函数

# sum某一维度聚合

>>> a=[[4,2,7],[1,3,0]]

>>> list(map(lambda ae:sum(ae),a))

[13, 4]

map和join函数

# map 和 join 实现串接list

>>> ','.join(map(lambda e:str(e),['001',1.8,'male','Hebei']))

'001,1.8,male,Hebei'

reduce函数

# 聚合

# lambda 参数个数必须为2

>>> from functools import reduce

>>> reduce(lambda x,y:str(x)+','+str(y)+'\\', [3,4,5,1])

'3,4\\,5\\,1\\'

enumerate 和 zip函数

# 打印索引值

>>> for i,e in enumerate([4,3,1]):

... print(i,e)

...

0 4

1 3

2 1

>>> a

[[4, 2, 7], [1, 3, 0]]

>>> for i,j in zip(a[:-1],a[1:]):

... print(i)

...

[4, 2, 7]

type 和 isinstance函数

>>> isinstance({'a':3},dict)

True

>>> isinstance({'a':3},set)

False

你可能感兴趣的:(python,常见函数)