常用的python内置函数

本文深入解析Python内置函数,如abs(), all(), any(), bin(), bool(), bytes(), bytearray(), callable(), chr(), ord(), exec(), dir(), divmod(), filter(), map(), functools.reduce(), frozenset(), globals(), hash(), hex(), oct(), round(), sorted(), zip(), import(), eval()等的使用方法与应用场景,助你提升Python编程技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常见的python内置函数

abs(),绝对值函数

all(), 列表的元素都为真的时候返回真,对于数字说0为假,非0为真

#!/usr/bin/python3
# -*- coding:UTF-8 -*-
print(all([0,-5,3]))

False
#!/usr/bin/python3
# -*- coding:UTF-8 -*-
print(all([1,-5,3]))

True

any(),列表中的元素有一个为真的时候为真

bin(), 十进制转成二进制

#!/usr/bin/python3
# -*- coding:UTF-8 -*-
a=bin(8)
print(a)

0b1000

bool() 判断是否为假,0是假,空列表也是假

#!/usr/bin/python3
# -*- coding:UTF-8 -*-
a=bool(1)
print(a)
a=bool(0)
print(a)
a=bool([])
print(a)

True
False
False

byte(), 将字符串变为字节

#!/usr/bin/python3
# -*- coding:UTF-8 -*-
a=bytes("huan feng",encoding="utf-8")
print(a)

b'huan feng'

bytearray(), 将字符串变成字节列表,这个列表是可以修改的

#!/usr/bin/python3
# -*- coding:UTF-8 -*-
a=bytearray("huan feng",encoding="utf-8")
print(a)
a[0]=97
print(a)

bytearray(b'huan feng')
bytearray(b'auan feng')

callable(), 判断是否可以被调用,什么是可以被调用?

就是后面可以加上()的就是可以运行的,就是可以被调用的

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

def fun():
    pass
a=callable([])
print(a)
b=callable(fun)
print(b)

False
True

我们可以看到方法是可以被调用的

char()和ord()可以按照ascii码表进行转换

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

print(chr(97))
print(ord('a'))

a
97

exec(),如果一个字符串是一段代码,可以使用该方法运行这个字符串中的代码

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

code="""
print(chr(97))
print(ord('a'))
"""
exec(code)

a
97

dir()显示变量的所有方法,包含一些隐藏的方法

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

code="""
print(chr(97))
print(ord('a'))
"""
print(dir(code))

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__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', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

dvmod(a,b) a除以b等于c余d,结果(c,d)

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

print(divmod(5,3))

(1, 2)

filter()和lambd搭配使用,可以对其进行列表封装

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

list=filter(lambda n:n>5,range(10))
for i in list:
    print(i)

6
7
8
9

这个运行的流程是:

将range(10)列表传递给匿名函数,然后只要n>5的,然后对其进行列表封装

map()和lambd搭配使用

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

list=map(lambda n:n*2,range(5))
for i in list:
    print(i)

0
2
4
6
8

将range(5)中的数据,交给前面的匿名函数处理吗,每一个与2进行相乘封装成一个新的列表

functools.reduce和lambda

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

import functools
res=functools.reduce(lambda x,y:x*y,range(1,9))
print(res)
res1=functools.reduce(lambda x,y:x+y,range(10))
print(res1)

40320
45

第一个:匿名函数有两个参数x,y,x表示x*y,y表示range(1,9)中的每一个值,最后返回x,表示阶乘

第二个:匿名函数有两个参数x,y,x表示x+y,y表示range(10)中的每一个值,最后返回x,表示和

列表是可以增加、减少及修改元素的,但是使用frozenset之后列表就不可以改变了,就类似set元组一样

list=[1,2,3]
list1=frozenset(list)

globals()返回文件中所有全局变量的key:value形式,变量名是key,变量名值是value

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

print(globals())

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000164AEC77518>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Users/TXB/PycharmProjects/TXB-1/test-2/test-3.py', '__cached__': None}

hash(), 将一个变量以hash表示

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

print(hash("huanfeng"))

5025799655801281939

hex(), 将一个数字转成十六进制

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

print(hex(11))

0xb

oct(), 将一个数字转成8进制

round(), 四舍五入

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

print(round(12.455))
print(round(12.455,2))

12
12.46

sorted()

#!/usr/bin/python3
# -*- coding:UTF-8 -*-
a={6:1,3:5,7:2}
list=a.items()#字典变列表
print(sorted(list))
print(sorted(list,key=lambda  x:x[1]))

[(3, 5), (6, 1), (7, 2)]
[(6, 1), (7, 2), (3, 5)]

字典是无序的,所以没有办法排序,但是可以使用items()方法将字典转成列表,列表是有序的,可以对其进行排序,排序默认是按照原来字典的建来排的,如果想要按值来排序可以使用下面的方式key=lambda x:x [1],x相当于列表中每一个元素,x[1]表示元素中的值。

zip()

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

a=[1,2,3,4]
b=['a','b','c','d','e','f']
for i in zip(a,b):
    print(i)

(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')

将两个列表拼接起来

import()方法

导入文件所使用的方法

eval()

将字符串string对象转化为有效的表达式参与求值运算返回计算结果

#!/usr/bin/python3
# -*- coding:UTF-8 -*-

str="""
[1,2,3,4]
"""
list=eval(str)
print(list[0])

1

这样就将字符串中的列表变成一个真的列表了,就相当于脱离了字符串的约束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值