Python中内置函数的用法
Python中内置函数是指Python标准库中提供的一组函数,在使用时无需导入任何模块,可以直接调用。这些内置函数是Python语言的核心功能之一,涵盖了各种类型的操作,如数学运算、字符串处理、列表操作、字典操作、文件操作等等,可以大大简化编程工作。
以下是一些常用内置函数的用法:
1. abs(x):返回x的绝对值
>>> abs(-10) 10 >>> abs(10) 10
2. len(s):返回s的长度,可以是字符串,列表,元组等
>>> len('hello')
5
>>> len([1,2,3])
3
3. range(start, stop, step):生成从start到stop,以step为步长的整数序列
>>> range(0, 10, 2) range(0, 10, 2) >>> list(range(0, 10, 2)) [0, 2, 4, 6, 8]
4. max(iterable):返回iterable中最大的元素
>>> max([1,2,3,4])
4
>>> max('hello')
'o'
5. min(iterable):返回iterable中最小的元素
>>> min([1,2,3,4])
1
>>> min('hello')
'e'
6. sum(iterable):返回iterable中所有元素的和
>>> sum([1,2,3,4]) 10
7. round(x, n):将x四舍五入到n位小数
>>> round(3.1415926, 2) 3.14 >>> round(3.1415926, 4) 3.1416
8. type(obj):返回obj的类型
>>> type('hello')
<class 'str'>
>>> type(1)
<class 'int'>
>>> type([])
<class 'list'>
9. isinstance(obj, class):判断obj是否为class类型的实例
>>> isinstance('hello', str)
True
>>> isinstance(1, str)
False
>>> isinstance([], list)
True
10. sorted(iterable, key=None, reverse=False):返回一个排序后的可迭代对象,可以使用key参数指定排序的依据,使用reverse参数指定是否降序排列
>>> sorted([3,1,4,1,5,9])
[1, 1, 3, 4, 5, 9]
>>> sorted('hello', reverse=True)
['o', 'l', 'l', 'e', 'h']
>>> sorted(['one', 'two', 'three', 'four'], key=len)
['one', 'two', 'four', 'three']
11. zip(*iterables):将多个可迭代对象的元素一一对应打包成元组,返回一个可迭代的zip对象
>>> zip([1,2,3], [4,5,6])
<zip object at 0x7ff5ac1d3e00>
>>> list(zip([1,2,3], [4,5,6]))
[(1, 4), (2, 5), (3, 6)]
>>> list(zip('hello', [1,2,3]))
[('h', 1), ('e', 2), ('l', 3)]
12. map(function, iterable):将function应用到iterable的每个元素上,返回一个可迭代的map对象
>>> def square(x): ... return x*x ... >>> map(square, [1,2,3]) <map object at 0x7ff5ac1d71c0> >>> list(map(square, [1,2,3])) [1, 4, 9]
13. filter(function, iterable):将function应用到iterable的每个元素上,保留返回True的元素,返回一个可迭代的filter对象
>>> def even(x): ... return x%2 == 0 ... >>> filter(even, [1,2,3,4,5,6]) <filter object at 0x7ff5ac1d7580> >>> list(filter(even, [1,2,3,4,5,6])) [2, 4, 6]
14. reduce(function, iterable):将function应用到iterable的前两个元素上,得到结果后再将结果与第三个元素应用function,一直迭代到iterable的最后一个元素,返回最终的结果
>>> from functools import reduce >>> def add(x, y): ... return x+y ... >>> reduce(add, [1,2,3,4]) 10
以上是一些常用的Python内置函数,可以帮助我们快速完成各种编程任务。同时,在实际开发中,我们也可以通过自定义函数来利用这些内置函数,进一步提高代码的简洁性和可读性。
