Python基础函数

1、绝对值abs()

2、比较大小函数cmp(x,y) 

x<y,返回-1;x==y,返回0;x>y,返回1

3、求和sum(L)

4、转换成字符串函数str(123) 》 '123'

5、转换成整数函数int('123') 》 123

注意:10/4 = 2,10.0/4 = 2.5,1+2=3,1+2.0=3.0

引入新版本特性__future__之后

from __future__ import division

print 10/4 》2.5

print 10//4 》2

6、自定义函数def 函数名():   函数体

7、引入match包 import math,math包中的函数:正弦函数math.sin(),余弦函数math.cos(),计算平方根math.sqrt()

8、递归函数:def fact(n): 

        if n==1: 

          return 1

        return  n*fact(n-1)

递归函数存在栈溢出问题

9、range()函数创建数列range(1,11) 》[1,2,3,4,5,6,7,8,9,10]

10、字母变大写函数upper()函数,'abc'.upper() 》'ABC'

11、长度函数length(),length(L)

12、zip()函数把两个list合并成一个list,zip([1,2,3],['A','B','C']) 》[(1,'A'),(2,'B'),(3,'C')]

13、enumerate()函数,enumerate(L)把L=['A','B','C']变成类似L=[(0,'A'),(1,'B'),(2,'C')]

14、迭代dict的value值,d.values()或者d.itervalues()

15、迭代dict的key和value值,d.items()或者d.iteritems()

16、判断变量是否是字符串 isinstance(x,str)

17、map(f,list)

它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回。

18、reduce(f,list)

和 map()类似,一个函数 f,一个list,但行为和 map()不同,reduce()传入的函数 f 必须接收两个参数,reduce()对list的每个元素反复调用函数f,并返回最终结果值。

19、filter(f,list)

接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。

20、sorted(list,f)

无论f中作何操作,sorted只排序不改变原数列

21、math函数,math.sin(),math.cos,math.pow(),math.log()...

import math                       只导入sin函数------>       from math import sin

print math.sin(0.5)                                                    print sin(0.5)(注意不能用math.sin,这里只导入了sin函数,没有导入math,否则会报错math没有定义)

》0.479425538604                                                  》0.479425538604

22、判断文件是否存在os.path的isdir,isfile函数

from os.path import isdir,isfile

print isdir(r'D:SoftWareJmeterapache-jmeter-5.0')  》True判断是否是目录

print isfile(r'D:SoftWareJmeterjson.txt')  》True判断是否是文件

23、判断数据类型isinstance()和type

print isinstance('a',str) 》print True

print type('a')  》 <type 'str'>

24、处理json文件的四个函数import json

json.dumps()将字典转化为字符串

json.loads()将字符串转化为字典

json.dump()写入json文件

json.load()读取json文件

参见https://www.cnblogs.com/xiaomingzaixian/p/7286793.html

25、匿名函数lambda

lambda x:x*x 

等价于

def f(x):

      return x*x

原文地址:https://www.cnblogs.com/hpzyang/p/10172433.html