概述
Python 提供了一组内置函数,简化了常见的编程任务。本指南对一些这些基本函数进行了分类和解释。
- 基本函数
print()
:将指定的消息打印到屏幕或其他标准输出设备。
print("Hello, World!") # 输出:Hello, World!
input()
: 允许用户从控制台输入数据。
name = input("请输入您的名字: ")
print(f"你好, {name}!")
len()
:返回对象或可迭代对象的长度(项目数量)。
my_list = [1, 2, 3, 4]
print(len(my_list)) # 输出:4
type()
:返回对象的类型。
print(type(10)) # 输出: <class 'int'>
print(type(3.14)) # 输出: <class 'float'>
print(type("hello")) # 输出: <class 'str'>
id()
:返回指定对象的唯一标识符。
id(my_list)
repr()
:返回对象的可读版本,即通过将对象转换为字符串来返回对象的可打印表示。
repr(my_list) # 输出: '[1, 2, 3, 4]'
数据类型转换
int()
: 将值转换为整数。
print(int("123")) # 输出: 123
float()
将一个值转换为浮点数。
print(float("123.45")) # 输出: 123.45
str()
: 将一个值转换为字符串。
print(str(123)) # 输出: '123'
bool()
: 将任何其他数据类型的值(字符串、整数、浮点数等)转换为布尔数据类型。
- 假值:0,NULL,空列表、元组、字典等。
- 真值:所有其他值将返回真。
print(bool(1)) # 输出: True
list()
: 将一个值转换为列表。
print(list("hello")) # 输出: ['h', 'e', 'l', 'l', 'o']
tuple()
:将一个值转换为元组。
print(tuple("hello")) # 输出: ('h', 'e', 'l', 'l', 'o')
set()
: 将一个值转换为集合(无序不重复元素的集)。
print(set("hello")) # 输出: {'e', 'l', 'o', 'h'}
dict()
:用于创建一个新的字典或将其他可迭代对象转换为字典。
dict(One = "1", Two = "2") # 输出:{'One': '1', 'Two': '2'}
dict([('a', 1), ('b', 2), ('c', 3)], d=4) # 输出:{'a': 1, 'b': 2, 'c': 3, 'd': 4}
- 数学函数
abs()
:返回一个数的绝对值。
print(abs(-7)) # 输出:7
round()
:返回一个数的绝对值。
print(round(3.14159, 2)) # 输出:3.14
min()
: 返回可迭代对象中的最小项或两个或多个参数中的最小值。
print(min([1, 2, 3, 4, 5])) # 输出: 1
max()
: 返回可迭代对象中的最大项或两个或多个参数中的最大值。
print(max([1, 2, 3, 4, 5])) # 输出: 5
sum()
: 从左到右对可迭代对象的项进行求和,并返回总和。
print(sum([1, 2, 3, 4, 5])) # 输出: 15
pow()
: 返回一个数的值,该数被另一个数作为指数所幂。
print(pow(2, 3)) # 输出: 8
- 序列函数
enumerate()
: 为可迭代对象添加计数器,并将其作为枚举对象返回。
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
# 输出:
# 0 apple
# 1 banana
# 2 cherry
zip()
:将多个可迭代对象组合成一个元组的单一迭代器。
names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]
for name, age in zip(names, ages):
print(f"{name} 是 {age} 岁")
# 输出:
# Alice 是 24 岁
# Bob 是 50 岁
# Charlie 是 18 岁
sorted()
: 从任何可迭代对象的元素中返回一个排序后的列表。
print(sorted([5, 2, 9, 1])) # 输出: [1, 2, 5, 9]
reversed()
: 返回一个反向迭代器。
print(list(reversed([5, 2, 9, 1])))
# 输出: [1, 9, 2, 5]
range()
: 生成一个数字序列。
for i in range(5):
print(i)
# 输出: 0, 1, 2, 3, 4
- 对象和类函数
isinstance()
: 检查一个对象是否是某个类或类元组的实例或子类。
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog)) # True
print(isinstance(dog, Animal)) # True
print(isinstance(dog, str)) # False
issubclass()
: 检查一个类是否是另一个类的子类。
print(issubclass(Dog, Animal)) # True
print(issubclass(Dog, object)) # True
print(issubclass(Animal, Dog)) # False
hasattr()
:检查对象是否具有指定的属性。
class Car:
def __init__(self, model):
self.model = model
car = Car("丰田")
print(hasattr(car, "model")) # True
print(hasattr(car, "color")) # False
getattr()
: 返回对象指定属性的值。
print(getattr(car, "model")) # 丰田
print(getattr(car, "color", "未知")) # 未知(默认值)
setattr()
:设置对象指定属性的值。
setattr(car, "color", "Red")
print(car.color) # Red
delattr()
:从对象中删除指定属性。
delattr(car, "color")
print(hasattr(car, "color")) # False
- 函数式编程
lambda
:用于创建小型匿名函数。
add = lambda a, b: a + b
print(add(3, 5)) # 8
map()
:将一个函数应用于可迭代对象中的所有项。
numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared)) # [1, 4, 9, 16]
filter()
:从可迭代对象的元素中构造一个迭代器,该迭代器的元素是函数返回
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # [2, 4, 6]
I/O 操作
open()
: 打开一个文件并返回相应的文件对象。
write()
: 向文件写入数据。
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()
close()
:关闭一个打开的文件。
file = open("example.txt", "r")
print(file.read()) # 行 A\n行 B\n行 C
file.close()
print(file.closed) # True
read()
: 从文件中读取数据。
file = open("example.txt", "r")
content = file.read()
print(content) # 你好,世界!
file.close()
file = open("example.txt", "w")
file.write("Line 1\nLine 2\nLine 3")
file.close()
file = open("example.txt", "r")
print(file.readline()) # Line 1
print(file.readline()) # Line 2
在这个示例中,我们首先以写入模式打开了一个名为 `example.txt` 的文件,并写入了三行文本。然后,我们关闭了文件。接着,我们以读取模式重新打开该文件,并逐行读取内容,打印出第一行和第二行。
file.close()
readlines()
file = open("example.txt", "r")
lines = file.readlines()
print(lines) # ['Line 1\n', 'Line 2\n', 'Line 3']
file.close()
writelines()
以下是您提供的英文技术文章内容的中文翻译:
lines = ["Line A\n", "Line B\n", "Line C\n"]
file = open("example.txt", "w")
file.writelines(lines)
file.close()
file = open("example.txt", "r")
请注意,代码块和格式保持不变,翻译内容已按照要求进行处理。
print(file.read()) # 行 A\n行 B\n行 C
file.close()
with
with open("example.txt", "w") as file:
file.write("Hello, world!")
# 不需要调用 file.close(),它会自动完成
内存管理
del()
: 删除一个对象。
x = 10
print(x) # 输出: 10
del x
# print(x) # 这将引发 NameError,因为 x 已被删除。
globals()
: 返回一个表示当前全局符号表的字典。
def example_globals():
a = 5
print(globals())
example_globals()
# 输出: {'__name__': '__main__', '__doc__': None, ...}
`locals()`: 更新并返回一个表示当前局部符号表的字典。
def example_locals():
x = 10
y = 20
print(locals())
example_locals()
# 输出: {'x': 10, 'y': 20}
vars()
: 返回给定对象的 dict 属性。
class Example:
def __init__(self, a, b):
self.a = a
self.b = b
e = Example(1, 2)
print(vars(e)) # 输出: {'a': 1, 'b': 2}
杂项
help()
: 调用内置帮助系统。
help(len)
# 输出:内置函数 len 在模块 builtins 中的帮助信息:
# len(obj, /)
# 返回容器中的项目数量。
dir()
: 尝试返回对象的有效属性列表。
print(dir([]))
# 输出: ['__add__', '__class__', '__contains__', ...]
eval()
: 解析传递给它的表达式并在程序中运行 Python 表达式。
x = 1
expression = "x + 1"
result = eval(expression)
print(result) # 输出: 2
exec()
:执行动态创建的程序,该程序可以是字符串或代码对象。
code = """
for i in range(5):
print(i)
"""
exec(code)
# 输出:
# 0
# 1
# 2
# 3
# 4
compile()
:将源代码编译成代码或AST对象。
source = "print('你好,世界!')"
code = compile(source, '<string>', 'exec')
exec(code)
# 输出: Hello, World!
结论
Python 的内置函数是促进各种编程任务的重要工具。从基本操作到复杂的函数式编程技术,这些函数使得 Python 变得灵活而强大。熟悉这些函数可以提高编码的效率和有效性,使您能够编写更简洁、更易维护的代码。