Python常用内置函数

1 类型转换函数

  1. int(a, base=10)
    用于将一个符合数字规范的字符串或数字转换为整型,参数base表示进制数,默认为十进制,base参数仅针对a参数是字符串时使用,若a参数是数字时使用base参数则会报错。
>>> int()
0
>>> int(1.25)
1
>>> int(10, 16)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
>>> int('10', 16)
16
  1. float([a])
    用于将一个符合数字规范的字符串或整数转换为浮点数
>>> float()
0.0
>>> float(22)
22.0
>>> float('125')
125.0
>>> float('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'abc'
  1. str([a])
    将对象转换为可阅读的样式,将数字转换为字符串,若无参数返回’’
>>> str()
''
>>> str(1234)
'1234'
>>> str(type)
"<class 'type'>"
>>> str('1234')
'1234'
  1. bool([a])
    将参数转换为bool类型,无参数返回False
>>> bool()
False
>>> bool('')
False
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(1)
True
  1. tuple([iterable])
    根据传入的可迭代参数创建一个新的元组,无参数返回空元组
>>> tuple()
()
>>> tuple('abcde')
('a', 'b', 'c', 'd', 'e')
>>> tuple([1,2,3,4,5])
(1, 2, 3, 4, 5)
  1. list([iterable])
    根据传入的可迭代参数创建一个新的列表,无参数返回空列表
>>> list()
[]
>>> list('abcde')
['a', 'b', 'c', 'd', 'e']
>>> list((1,2,3,4,5))
[1, 2, 3, 4, 5]
  1. dict([iterable])
    根据传入的符合字典规范的参数创建一个新的字典,无参数返回空字典
>>> dict([iterable])
{}
>>> dict(x=1,y=2,z=3)
{'x': 1, 'y': 2, 'z': 3}
>>> dict(zip(['x','y','z'],['1','2','3']))
{'x': '1', 'y': '2', 'z': '3'}
  1. set([iterable])
    根据传入参数创建一个新的集合
>>> set()
set()
>>> set('abcde')
{'b', 'd', 'a', 'e', 'c'}
  1. frozenset([iterable])
    返回一个冻结的set集合,不能添加、删除和修改集合的元素
>>> frozenset()
frozenset()
>>> frozenset('12345')
frozenset({'2', '4', '3', '1', '5'})

2 数学相关函数

  1. sum(iterable[,start])
    对序列进行求和运算
>>> sum([1,2,3,4])
10
>>> sum([1,2,3,4], 10)
20
>>> sum([1,2,3,4], 20)
30
>>> sum(range(101))
5050
  1. abs(a)
    求传入参数的绝对值
>>> abs(1)
1
>>> abs(-1)
1
>>> abs(1.25)
1.25
>>> abs(-1.25)
1.25
  1. round(a[,n])
    返回传入参数的四舍五入值,n参数表示保留几位小数,若不传则不保留小数
>>> round(1)
1
>>> round(1.2458)
1
>>> round(1.2458,2)
1.25
  1. min(a[,b,c,…])
    返回传入参数的最小值
>>> min(1,2,3,4)
1
  1. max(a[,b,c,…])
    返回传入参数的最大值
>>> min(1,2,3,4)
4
  1. divmod(a, b)
    返回 a / b 的商数和余数的数组
>>> divmod(5, 2)
(2, 1)
>>> divmod(2, 5)
(0, 2)
>>> divmod(-5, -2)
(2, -1)
>>> divmod(-2,- 5)
(0, -2)
  1. pow(a, b[,c])
    返回a的b次方,若参数c存在,则结果为:pow(a, b) % c
>>> pow(2, 3)
8
>>> pow(2, 3, 5)
3
>>> pow(2, -3)
0.125
>>> pow(-2, 3)
-8
  1. bin(a)
    返回一个整数的二进制表示
>>> bin(1)
'0b1'
>>> bin(2)
'0b10'
>>> bin(3)
'0b11'
  1. oct(a)
    将一个整数转换为八进制
>>> oct(1)
'0o1'
>>> oct(7)
'0o7'
>>> oct(8)
'0o10'
>>> oct(1.1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
  1. hex(a)
    将一个整数转换为十六进制
>>> hex(1)
'0x1'
>>> hex(15)
'0xf'
>>> hex(16)
'0x10'
>>> hex(1.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
  1. chr(i)
    根据传入的数字返回一个字符,数字的范围为:0-255
>>> chr(100)
'd'
>>> chr(80)
'P'

3 序列相关函数

  1. len(object)
    返回对象长度
>>> len('abcde')
5
>>> len((1,2,3,4,5))
5
>>> len([1,2,3,4,5])
5
  1. sorted(iterable, cmp=None, key=None, reverse=False)
    对可迭代对象进行排序,但不改变对象的值,cmp:比较函数,key:比较元素,reverse:排序方式(False-升序,True-降序)
>>> s1 = [1,3,2,4]
>>> sorted(s1)
[1, 2, 3, 4]
>>> sorted(s1, reverse=True)
[4, 3, 2, 1]
>>> print(s1)
[1, 3, 2, 4]
  1. reversed(seq)
    反转序列
>>> s1 = [1,3,2,4]
>>>> list(reversed(s1))
[4, 2, 3, 1]
>>> print(s1)
[1, 3, 2, 4]
  1. range([start,] end [,step])
    返回一个整数列表,start:起始值,默认为0,end:终止值但不包括它,step:步长,默认1
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(1,5))
[1, 2, 3, 4]
>>> list(range(1,5,2))
[1, 3]
>>> list(range(5,1,-1))
[5, 4, 3, 2]
>>> list(range(5,0,-1))
[5, 4, 3, 2, 1]
  1. xrange([start,] end [,step])
    xrange与range完全一样,使用方法也一样,不同的是xrange是一个生成器,只有在需要用到的时候才生成列表,当列表非常大时可节省内存。
  2. zip([iterable,…])
    元组的迭代器,其中每个传递的迭代器中的第一项配对在一起,然后每个传递的迭代器中的第二项配对在一起,依此类推。如果传递的迭代器具有不同的长度,则项目数最少的迭代器将决定新迭代器的长度。
>>> a = ['a','b','c']
>>> b = [1,2,3]
>>> c = ['x','y','z']
>>> list(zip(a, b))
[('a', 1), ('b', 2), ('c', 3)]
>>> list(zip(a, b, c))
[('a', 1, 'x'), ('b', 2, 'y'), ('c', 3, 'z')]
  1. enumerate(iterable[,start])
    用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,参数start表示参数下标的起始位置(默认为0)
>>> a = ['a','b','c']
>>> list(enumerate(a))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> list(enumerate(a, 3))
[(3, 'a'), (4, 'b'), (5, 'c')]
  1. iter(a)
    创建迭代器
>>> a = iter(range(10))
>>> next(a)
0
>>> next(a)
1
>>> next(a)
2
  1. next(a)
    获取迭代器的下一元素
  2. all(iterable)
    判断传入的可迭代参数中是否含有元素为0、’’、False,若有返回False否则返回True,如果是空的迭代器则返回True。
>>> all([])
True
>>> all([0,1,2])
False
>>> all([1,2])
True
>>> all([1,2,''])
False
>>> all([1,2,False])
False
  1. slice
    返回一个切片对象,主要用在切片操作函数里的参数传递
>>> slice(10)
slice(None, 10, None)
>>> slice(5)
slice(None, 5, None)
  1. any(iterable)
    判断传入的迭代器是否全部为空元素(0、’’、False),若是返回False,否则返回True。空迭代器返回False.
>>> any([])
False
>>> any([1,2,''])
True
>>> any([1,0,''])
True
>>> any([0.00,0,''])
False
>>> any([False,0,''])
False
  1. cmp(a, b)
    比较两个对象的大小,a < b返回-1,a = b返回0,a > b则返回1
>>> cmp(1,2)
-1
>>> cmp(1,1)
0
>>> cmp(2,1)
1
  1. filter(function or None, sequence)
    过滤不符合的数据,返回有符合元素组成的序列
#过滤大于10的数
def max(s) :
    return s > 10
print filter(max, range(20))
  1. map(function, sequence[, sequence, …])
    将传入的函数应用到序列中的所有的项。可应用多个序列,若传入的函数为None时,将序列中的元素合并起来,返回一个新的元祖
def add(a,b):
    return a+b
print map(add, [1,2],[3,4])
print map(None, [1,2],[3,4])

程序运行结果:
[4, 6]
[(1, 3), (2, 4)]

4 对象操作函数

  1. help([object])
    查看函数或模块用途的详细说明
>>> help(map)
Help on class map in module builtins:

class map(object)
 |  map(func, *iterables) --> map object
 |
 |  Make an iterator that computes the function using arguments from
 |  each of the iterables.  Stops when the shortest iterable is exhausted.
 |
 |  Methods defined here:
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __iter__(self, /)
 |      Implement iter(self).
 |
 |  __next__(self, /)
 |      Implement next(self).
 |
 |  __reduce__(...)
 |      Return state information for pickling.
 |
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
  1. dir([object])
    收集对象信息。若参数返回当前范围的变量、方法和定义等对象列表信息,有参数则返回参数的属性,方法列表。
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'c', 'l', 's1']
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
  1. id([object])
    获取对象的内存地址
>>> id(str)
140731903546480
>>> id(int)
140731903532592
>>> id(20)
140731905009032
>>> id('abcd')
2214530453872
  1. type(name,bases,dict)
    若函数只有1个参数返回对象的类型,若函数有3个参数则返回新的类对象
>>> type(int)
<class 'type'>
>>> type(123)
<class 'int'>
>>> type([1,2])
<class 'list'>
>>> type({1:'A',2:'B'})
<class 'dict'>
  1. hash([object])
    获取对象哈希值
>>> hash(int)
8795743970787
>>> hash(123)
123
>>> hash('123')
-9091588337232062468
  • 26
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值