来源:
http://www.hlkjfj.com
http://8k.zjdulou.com
http://r.zjdulou.com
http://s.zjdulou.com
http://tiyu.zjdulou.com
Python内置函数是Python解释器预先定义的函数,无需导入任何模块即可直接使用。它们提供了基础且强大的功能,覆盖数据类型处理、数学运算、对象操作等多个方面。
len()
- 获取长度返回对象(字符串、列表、元组等)的长度或元素个数。
# 字符串长度
text = "Python"
print(len(text)) # 输出: 6
# 列表元素个数
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # 输出: 5
# 字典键值对数量
user = {"name": "Alice", "age": 30}
print(len(user)) # 输出: 2
range()
- 生成序列生成一个不可变的数字序列,常用于for循环中。
# 生成0-4的序列
for i in range(5):
print(i) # 输出: 0 1 2 3 4
# 生成5-9的序列
for i in range(5, 10):
print(i) # 输出: 5 6 7 8 9
# 生成0-10的偶数
even_numbers = list(range(0, 11, 2))
print(even_numbers) # 输出: [0, 2, 4, 6, 8, 10]
print()
- 输出内容将指定的内容打印到控制台,是最常用的调试和输出方法。
# 基本输出
print("Hello, Python!") # 输出: Hello, Python!
# 输出多个值
name = "Alice"
age = 30
print("Name:", name, "Age:", age) # 输出: Name: Alice Age: 30
# 格式化输出
print(f"{name} is {age} years old.") # 输出: Alice is 30 years old.
# 输出到文件
with open('output.txt', 'w') as f:
print("Save to file", file=f)
Python 3.11 共有69个内置函数,按功能分类如下:
类别 | 函数列表 | 说明 |
---|---|---|
数据类型转换 | int(), float(), str(), bool(), list(), tuple(), set(), dict(), bin(), hex(), complex() | 在不同数据类型之间进行转换 |
数学运算 | abs(), divmod(), max(), min(), pow(), round(), sum() | 执行基本数学计算 |
迭代与循环 | enumerate(), filter(), iter(), map(), next(), range(), reversed(), sorted(), zip() | 处理可迭代对象和序列 |
对象操作 | id(), isinstance(), issubclass(), type(), len(), hash() | 检查和操作对象属性 |
输入输出 | input(), open(), print() | 处理输入输出操作 |
其他功能 | callable(), exec(), eval(), help(), dir(), globals(), locals(), vars() | 提供高级功能和内省 |
内置函数通常比自定义函数更高效,经过优化且无错误。例如,使用sorted()
而不是自己实现排序算法。
内置函数可以组合使用,实现更复杂的功能。例如:
# 获取字符串中最长的单词
text = "Python built-in functions are powerful"
longest_word = max(text.split(), key=len)
print(longest_word) # 输出: functions
虽然内置函数强大,但某些情况下自定义函数可读性更好。例如,复杂逻辑使用自定义函数比嵌套多个内置函数更清晰。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。