python 基础笔记十四 - 内置函数(部分函数)

1、bool():转换为布尔类型,遵循“非空即真”原则

1 print(bool())  #False
2 print(bool('')) #False
3 print(bool([])) #False
4 print(bool('test')) #True

2、max():选取最大值

   min():选取最小值

1 print(max([2,5,88,53,66,4])) #88
2 print(min(['ab','ac','db','fa'])) #ab
3 print(min('d225552442')) #2

3、round():取小数点后几位

1 print(round(3.14158563,2)) #3.14

4、sorted():排序,默认升序排序,加上reverse=True参数进行降序排序

      reversed():翻转函数

1 s = '5223341145698'
2 print(sorted(s))  #['1', '1', '2', '2', '3', '3', '4', '4', '5', '5', '6', '8', '9']
3 print(sorted(s,reverse=True))   #['9', '8', '6', '5', '5', '4', '4', '3', '3', '2', '2', '1', '1']
4 print(list(reversed(sorted(s)))) #['9', '8', '6', '5', '5', '4', '4', '3', '3', '2', '2', '1', '1']

5、ord():将字符转换为ASCII码对应的数字

     chr():将ASCII码的数字转换为字符

1 print(ord('b')) #ascill码:98
2 print(chr(67))  #字符:C

 6、any():如果这个list里面有一个为真,就返回true

       all():如果这个list里面有一个不为真,就返回false

1 res = any([1,2,0]) #如果这个list里面有一个为真,就返回true
2 print(res)  #True
3 res = all([1,4,2,0,5]) #如果这个list里面有一个不为真,就返回false
4 print(res)  #False

7、dir():打印变量或者模块拥有哪些方法

1 print(dir(xlwt))

8、eval():用来执行一个字符串表达式,并返回表达式的值

1 print(eval('5+9'))  #14
2 print(eval('[1,5,6]'))  #[1, 5, 6]
3 print(eval('{"id":2,"name":"tom"}')) #{'id': 2, 'name': 'tom'}
4 
5 f = open('test.txt').read()  #文件内容:{'id':2,'name':'tom'}
6 print(eval(f))  #{'id': 2, 'name': 'tom'}

9、 exec():执行较复杂的Python代码,参数是字符串类型

1 my_code = '''
2 def my():
3     print('运行...')
4 my()
5 '''
6 exec(my_code)

10、map():根据提供的函数对指定序列做映射,第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。

  返回值是迭代器

1 l = [2,55,3,64,7]
2 def bl(i):
3     return str(i).zfill(2)
4 res = map(bl,l)   #将list中的每个元素作为参数传给方法,并将每个值的返回值作为新列表的元素
5 print(list(res))  #['02', '55', '03', '64', '07']

11、filter():用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

  该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。

 1 #过滤出列表中的所有奇数
 2 def is_odd(i):
 3     return i%2==1  #返回值为True或者False
 4 
 5 newlist = filter(is_odd,[1,3,6,8,9,4,7]) #将列表中的每个元素作为参数传给方法,将返回值为True的元素保存到新元素
 6 print(list(newlist))  #[1, 3, 9, 7]
 7 
 8 #过滤出1-100中平方根是整数的数
 9 import math
10 def is_sqr(x):
11     return math.sqrt(x)%1==0
12 newlist = filter(is_sqr,range(0,101)) #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
13 print(list(newlist))

猜你喜欢

转载自www.cnblogs.com/wu-xw/p/9790205.html