Python 是一种广泛使用的高级编程语言,它提供了大量的内置函数,这些函数可以帮助开发者高效地完成各种任务。以下是一些 Python 中常用的内置函数:
print():用于输出指定的消息到控制台。
python复制
print("Hello, World!")
len():返回对象(字符、列表、元组等)的长度。
python复制
len("Hello") # 输出 5
type():返回对象的类型。
python复制
type("Hello") # 输出 <class 'str'>
int(), float(), str():分别用于将其他数据类型转换为整数、浮点数和字符串。
python复制
int("10") # 输出 10 float("10.5") # 输出 10.5 str(10) # 输出 "10"
input():用于接收用户的输入。
python复制
name = input("请输入你的名字:") print("你好," + name)
range():生成一个整数序列,常用于循环中。
python复制
for i in range(5): print(i)
list(), tuple(), set(), dict():分别用于创建列表、元组、集合和字典。
python复制
list((1, 2, 3)) # 输出 [1, 2, 3] tuple([1, 2, 3]) # 输出 (1, 2, 3) set([1, 2, 2, 3]) # 输出 {1, 2, 3} dict(name="Alice", age=25) # 输出 {'name': 'Alice', 'age': 25}
max(), min():分别返回给定参数的最大值和最小值。
python复制
max([1, 2, 3]) # 输出 3 min([1, 2, 3]) # 输出 1
sum():返回给定参数的总和。
python复制
sum([1, 2, 3]) # 输出 6
sorted():返回一个排序后的列表,不改变原列表。
python复制
sorted([3, 1, 2]) # 输出 [1, 2, 3]
map():将函数应用于序列中的每个元素,并返回一个新的列表。
python复制
map(lambda x: x * 2, [1, 2, 3]) # 输出 [2, 4, 6]
filter():根据函数的返回值(True 或 False)来过滤序列中的元素。
python复制
filter(lambda x: x % 2 == 0, [1, 2, 3, 4]) # 输出 [2, 4]
reduce():对序列中的元素进行累积操作,需要从
functools
模块导入。python复制
from functools import reduce reduce(lambda x, y: x + y, [1, 2, 3, 4]) # 输出 10
open():用于打开文件。
python复制
file = open("example.txt", "r") content = file.read() file.close()
abs():返回数字的绝对值。
python复制
abs(-10) # 输出 10
round():返回浮点数四舍五入后的值。
python复制
round(3.7) # 输出 4
这些函数是 Python 编程中非常基础且常用的,掌握它们对于编写高效的 Python 代码至关重要。此外,Python 还有许多其他的内置函数和模块,可以根据需要进行学习和使用。