python 内置函数

本文详细介绍了Python的内置函数,包括abs()、all()、enumerate()和filter()等,展示了它们的使用方法和示例。通过这些函数,开发者可以更高效地处理数据和控制流程。同时,文章还解释了如何将函数应用于不同类型的数据,如整数、浮点数、字符串和列表,以及在处理可迭代对象时的过滤和索引操作。

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

python 内置函数

python 内置函数总览:

abs()delattr()hash()memoryview()set()
all()dict()help()min()setattr()
any()dir()hex()next()slice()
ascii()divmod()id()object()sorted()
bin()enumerate()input()oct()staticmethod()
bool()eval()int()open()str()
breakpoint()exec()isinstance()ord()sum()
bytearray()filter()issubclass()pow()super()
bytes()float()iter()print()tuple()
callable()format()len()property()type()
chr()frozenset()list()range()vars()
classmethod()getattr()locals()repr()zip()
compile()globals()map()reversed()__import__()
complex()hasattr()max()round()-


abs (x)

返回整数或者浮点数的绝对值

>>> abs(1)
1
>>> abs('1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
>>> abs(-1.1)
1.1
>>> abs(-1.0)
1.0
>>>
# 复数返回其大小
>>> abs(3+4j)  
5.0
>>>


all (iterable)

可迭代对象的所有元素都为真或者可迭代对象为空, 则返回True, 否则返回False

# 等同于如下代码
def all(its):
    for v in its:
        if not v:
            return False
    return True

# 命令行测试
>>> all([])
True
>>> all([1,2,3])
True
>>> all([1,2,0])
False
>>> all(['', 'a'])
False
>>> all(['b','a'])
True
>>>


enumerate (iterable, start=0)

传入可迭代对象, 然后给每个元素配上索引 (默认从 0 开始) 返回, 通常遍历用

# 等同于如下代码
def enumerate(its, start=0):
    n = start
    for v in its:
        yield n, v
        n += 1
        
# 测试
>>> enumerate('abc')
<enumerate object at 0x0000027574606318>
>>> list(enumerate('abc'))
[(0, 'a'), (1, 'b'), (2, 'c')]
>>> list(enumerate('abc', 1)) 
[(1, 'a'), (2, 'b'), (3, 'c')]
>>>  


filter (function, iterable)

用 function 去过滤 iterable 中的每个元素, 只保留结果为 True 的; 如果 function 为 None, 则过滤掉为假的元素(整型的0和浮点型的0.0; None对象类型; 空对象)

# 等同如下生成器表达式
# function (f) 非 None, iterable(its)
v for v in its if f(v)
    
# function 为 None, iterable(its)
v for v in its if v

# 测试
>>> list(filter(None, [1, 2, 3, '', None, [], {}, 0, 0.0]))
[1, 2, 3]
>>> list(filter(lambda x: x, [1, 2, 3, '', None, [], {}, 0, 0.0]))
[1, 2, 3]
>>> list(filter(lambda x: x < 4, [1, 2, 3, 4]))
[1, 2, 3]
>>>


float ([x])

把 x 转浮点型, 可接受的 x 值语法如下(忽略 x 前后空格):

持续更新…

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gnn_explorer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值