内置函数-max、min、round、sorted、ord、chr、any、all、dir、eval、exec、map、filter

http://www.nnzhp.cn/archives/152

1、max,min,round

1 print(max([3,4.563,3,6,2.5])) #取最大值,可循环参数即可,int类型的,字符串类型不行
2 print(min(9,4,7,1,0)) #取最小值
3 print(round(3.43535345,2)) #取即为小数,四舍五入
4 print(round(1.12345,2))

2、sorted

1 s = '235434125636234'
2 res = sorted(s) #对字符串排序,默认升序
3 print(list(res)) #需要转换下类型,打印
4 res = reversed(sorted(s))#reversed反转,降序排序
5 print(list(res))
6 print(sorted(s,reverse=True)) #降序也可以这样写,与上面写法效果一样。
#列表有.sort方法

3、ord、chr

1 print(ord('a'))#将字母转成阿斯克码里面的值
2 print(chr(97)) #把数字转成阿斯克码表里面的字母

4、any、all

1 res = any([1,2,3,4,0]) #如果这个循环迭代序列里面有一个为真的话,就返回true
2 print(res)
3 res = all([1,1,1,0,1])#如果这个循环迭代序列里面,全部为真,就返回true
4 print(res)
1 print(any((1,2,0))) #返回True
2 print(any((0,0,0))) #全部是0,返回False

5、dir获取帮助信息

1 import hashlib
2 m = hashlib.md5('abc'.encode())
3 print(dir(m)) #查看变量m的所有方法

6、eval 执行python代码,只能执行简单的,定义数据类型和运算

实例1:

1 # eval#执行python代码,只能执行简单的,定义数据类型和运算
2 print(eval('1+1'))
3 print(eval('{"a":"1"}'))

执行结果:

1 2
2 {'a': '1'}

实例2:

1 f = open('a.txt').read() #文件里面的内容是“{'username':'abc','password':'123456'}”,但是读出来是字符串
2 print(type(f))
3 print(f)
4 res = eval(f) #转数据类型
5 print(type(res))
6 print(res)

执行结果:

1 <class 'str'>
2 {'username':'abc','password':'123456'}
3 <class 'dict'>
4 {'username': 'abc', 'password': '123456'}

7、exec:执行python代码的,只要语法对,都能执行,不太安全

1 # 在线写代码:http://www.runoob.com/try/runcode.php?filename=HelloWorld&type=python3。这种会对敏感代码进行控制
2 my_code = '''  #前面写个变量,三引号作用于变量
3 def my():
4     print('运行程序')
5 my()
6 '''
7 exec(my_code) #执行python代码的,这种方式不安全
运行程序

 8、map 

map是循环帮你调用函数,然后保存函数的返回值,python3中,返回的值放到了一个生成器里面。需要list强制类型转换下(能转成list或元组,集合等可变的类型)。
map后面传的可以循环就行(字符串、列表等)
实例:
写一个调用函数:
1 l = [1, 3, 4, 6, 2, 4, 7]
2 l2 = [] #定义一个空list存放补0后的值
3 def bl(i):  # 定义一个补0的函数
4     return str(i).zfill(2)
5 for i in l:
6     l2.append(bl(i))
7 print(l2)
['01', '03', '04', '06', '02', '04', '07']

上面这个可以用map写:

1 #另外用map写,帮你循环调用函数
2 l = [1, 3, 4, 6, 2, 4, 7]
3 l2 = list(map(bl,l))
4 # l2 = tuple(map(bl,l))
5 # l2 = set(map(bl,l)) #集合会去重
6 print(l2)
['01', '03', '04', '06', '02', '04', '07']

9、filter()

也是循环调用函数的,如果函数返回的值是真,那么就保存这个值.如果返回值假,则过滤掉(过滤你传过来的值)

实例1:上面的例子用filter过滤:
1 def bl(i):  # 定义一个补0的函数
2     return str(i).zfill(2)
3 l = [1, 3, 4, 6, 2, 4, 7]
4 l3 = list(filter(bl,l))
5 print(l3)

结果:返回的都是真,则全部值保留,list强制类型转换后,放在list中

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

实例2:

1 def bl(i):  # 定义一个补0的函数
2     if i >3:
3         return True
4 l = [1, 3, 4, 6, 2, 4, 7]
5 l3 = list(filter(bl,l)) #循环调用函数,过滤掉传入的list中小于3的值
6 print(l3)

结果:

[4, 6, 4, 7]

猜你喜欢

转载自www.cnblogs.com/once-again/p/9800745.html