Python中很常用的100个函数整理

Python 内置函数提供了强大的工具,涵盖数据处理、数学运算、迭代控制、类型转换等。本文总结了 100 个常用内置函数,并配备示例代码,提高编程效率。

  1. abs() 取绝对值
python 复制代码
print(abs(-10))  # 10
  1. all() 判断所有元素是否为真
python 复制代码
print(all([True, 1, "hello"]))  # True
print(all([True, 0, "hello"]))  # False
  1. any() 判断任意元素是否为真
python 复制代码
print(any([False, 0, "", None]))  # False
print(any([False, 1, ""]))  # True
  1. ascii() 返回对象的 ASCII 表示
python 复制代码
print(ascii("你好"))  # '\u4f60\u597d'
  1. bin() 十进制转二进制
python 复制代码
print(bin(10))  # '0b1010'
  1. bool() 转换为布尔值
python 复制代码
print(bool([]))  # False
print(bool(1))  # True
  1. bytearray() 创建字节数组
python 复制代码
ba = bytearray([65, 66, 67])
print(ba)  # bytearray(b'ABC')
  1. bytes() 创建不可变字节序列
python 复制代码
b = bytes("hello", encoding="utf-8")
print(b)  # b'hello'
  1. callable() 判断对象是否可调用
python 复制代码
def func(): pass
print(callable(func))  # True
print(callable(10))  # False
  1. chr() 获取 Unicode 码对应的字符
python 复制代码
print(chr(97))  # 'a'
  1. ord() 获取字符的 Unicode 编码
python 复制代码
print(ord('a'))  # 97
  1. complex() 创建复数
python 复制代码
print(complex(1, 2))  # (1+2j)
  1. dict() 创建字典
python 复制代码
d = dict(name="Alice", age=25)
print(d)  # {'name': 'Alice', 'age': 25}
  1. dir() 获取对象所有属性和方法
python 复制代码
print(dir([]))  # ['append', 'clear', 'copy', ...]
  1. divmod() 取商和余数
python 复制代码
print(divmod(10, 3))  # (3, 1)
  1. enumerate() 生成索引和值
python 复制代码
lst = ["a", "b", "c"]
for i, v in enumerate(lst):
    print(i, v)
  1. eval() 计算字符串表达式
python 复制代码
expr = "3 + 4"
print(eval(expr))  # 7
  1. filter() 过滤序列
python 复制代码
nums = [1, 2, 3, 4, 5]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums)  # [2, 4]
  1. float() 转换为浮点数
python 复制代码
print(float("3.14"))  # 3.14
  1. format() 格式化字符串
python 复制代码
print(format(10000, ","))  # '10,000'
21. frozenset() 创建不可变集合
fs = frozenset([1, 2, 3])
print(fs)
  1. globals() 获取全局变量
python 复制代码
print(globals())
  1. hasattr() 检查对象是否有属性
python 复制代码
class Person:
    name = "Alice"print(hasattr(Person, "name"))  # True
  1. hash() 获取哈希值
python 复制代码
print(hash("hello"))  
  1. help() 查看帮助
python 复制代码
help(print)
  1. hex() 十进制转十六进制
python 复制代码
print(hex(255))  # '0xff'
  1. id() 获取对象的唯一标识符
python 复制代码
a = 10
print(id(a))
  1. input() 获取用户输入
python 复制代码
name = input("请输入你的名字: ")
print("你好, " + name)
  1. int() 转换为整数
python 复制代码
print(int("123"))  # 123
  1. isinstance() 检查对象类型
python 复制代码
print(isinstance(123, int))  # True
  1. issubclass() 检查是否是子类
python 复制代码
class A: pass
class B(A): pass
print(issubclass(B, A))  # True
  1. iter() 获取迭代器
python 复制代码
lst = [1, 2, 3]
it = iter(lst)
print(next(it))  # 1
  1. len() 获取长度
python 复制代码
print(len([1, 2, 3]))  # 3
  1. list() 创建列表
python 复制代码
print(list("hello"))  # ['h', 'e', 'l', 'l', 'o']
  1. locals() 获取局部变量
python 复制代码
def func():
    a = 10
    print(locals())

func()
  1. map() 对序列中的每个元素进行操作
python 复制代码
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared)  # [1, 4, 9, 16]
  1. max() 返回最大值
python 复制代码
print(max([10, 20, 5]))  # 20
print(max("python"))  # 'y'
  1. min() 返回最小值
python 复制代码
print(min([10, 20, 5]))  # 5
print(min("python"))  # 'h'
  1. next() 获取迭代器的下一个元素
python 复制代码
it = iter([10, 20, 30])
print(next(it))  # 10
print(next(it))  # 20
  1. object() 创建一个新对象
python 复制代码
obj = object()
print(obj)  # <object object at 0x...>
  1. oct() 十进制转八进制
python 复制代码
print(oct(10))  # '0o12'
  1. open() 打开文件
python 复制代码
with open("test.txt", "w") as f:
    f.write("Hello, Python!")
  1. pow() 计算指数幂
python 复制代码
print(pow(2, 3))  # 8
print(pow(2, 3, 5))  # (2^3) % 5 = 3
  1. print() 打印输出
python 复制代码
print("Hello", "Python", sep="-")  # Hello-Python
  1. range() 生成范围序列
python 复制代码
print(list(range(1, 10, 2)))  # [1, 3, 5, 7, 9]
  1. repr() 返回对象的字符串表示
python 复制代码
print(repr("Hello\nWorld"))  # "'Hello\\nWorld'"
  1. reversed() 反转序列
python 复制代码
print(list(reversed([1, 2, 3, 4])))  # [4, 3, 2, 1]
  1. round() 四舍五入
python 复制代码
print(round(3.14159, 2))  # 3.14
  1. set() 创建集合
python 复制代码
print(set([1, 2, 2, 3]))  # {1, 2, 3}
  1. setattr() 设置对象属性
python 复制代码
class Person:
    pass
p = Person()
setattr(p, "age", 25)
print(p.age)  # 25
  1. slice() 创建切片对象
python 复制代码
lst = [10, 20, 30, 40]
s = slice(1, 3)
print(lst[s])  # [20, 30]
  1. sorted() 排序
python 复制代码
print(sorted([3, 1, 4, 2]))  # [1, 2, 3, 4]
print(sorted("python"))  # ['h', 'n', 'o', 'p', 't', 'y']
  1. staticmethod() 定义静态方法
python 复制代码
class Math:
    @staticmethod
    def add(x, y):
        return x + yprint(Math.add(3, 4))  # 7
  1. str() 转换为字符串
python 复制代码
print(str(123))  # '123'
print(str([1, 2, 3]))  # '[1, 2, 3]'
  1. sum() 计算总和
python 复制代码
print(sum([1, 2, 3, 4]))  # 10
  1. super() 调用父类方法
python 复制代码
class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        super().greet()
        print("Hello from Child")

c = Child()
c.greet()
  1. tuple() 创建元组
python 复制代码
print(tuple([1, 2, 3]))  # (1, 2, 3)
  1. type() 获取对象类型
python 复制代码
print(type(123))  # <class 'int'>
  1. vars() 获取对象的 dict 属性
python 复制代码
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = agep = Person("Alice", 25)
print(vars(p))  # {'name': 'Alice', 'age': 25}
  1. zip() 合并多个可迭代对象
python 复制代码
names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages)))  # [('Alice', 25), ('Bob', 30)]
  1. import() 动态导入模块
python 复制代码
math_module = __import__("math")
print(math_module.sqrt(16))  # 4.0
  1. delattr() 删除对象的属性
python 复制代码
class Person:
    age = 25
delattr(Person, "age")
print(hasattr(Person, "age"))  # False
  1. exec() 执行字符串代码
python 复制代码
code = "x = 10\ny = 20\nprint(x + y)"
exec(code)  # 30
  1. memoryview() 创建内存视图对象
python 复制代码
b = bytearray("hello", "utf-8")
mv = memoryview(b)
print(mv[0])  # 104
  1. round() 取整
python 复制代码
print(round(4.567, 2))  # 4.57
  1. breakpoint() 设置调试断点
python 复制代码
x = 10
breakpoint()  # 进入调试模式
print(x)
  1. classmethod() 定义类方法
python 复制代码
class Person:
    name = "Unknown"
    @classmethod
    def set_name(cls, name):
        cls.name = namePerson.set_name("Alice")
print(Person.name)  # Alice
  1. compile() 编译字符串为代码对象
python 复制代码
code = "print('Hello, World!')"
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code)  # Hello, World!
  1. complex() 创建复数
python 复制代码
c = complex(3, 4)
print(c)  # (3+4j)
  1. del 删除对象
python 复制代码
x = 10
del x
# print(x)  # NameError: name 'x' is not defined
  1. ellipsis 省略号对象
python 复制代码
def func():
    ...
print(func())  # None
  1. float.fromhex() 将十六进制转换为浮点数
python 复制代码
print(float.fromhex('0x1.8p3'))  # 12.0
  1. format_map() 使用映射对象格式化字符串
python 复制代码
class Person:
    age = 25
print(getattr(Person, "age"))  # 25
  1. getattr() 获取对象属性
python 复制代码
class Person:
    age = 25
print(getattr(Person, "age"))  # 25
  1. is 判断是否是同一个对象
python 复制代码
a = [1, 2, 3]
b = a
print(a is b)  # True
  1. issubclass() 判断是否是子类
python 复制代码
class A: pass
class B(A): passprint(issubclass(B, A))  # True
  1. iter() 创建迭代器
python 复制代码
lst = [1, 2, 3]
it = iter(lst)
print(next(it))  # 1
  1. len() 获取长度
python 复制代码
print(len([1, 2, 3]))  # 3
  1. memoryview() 创建内存视图
python 复制代码
b = bytearray("hello", "utf-8")
mv = memoryview(b)
print(mv[0])  # 104
  1. object() 创建基础对象
python 复制代码
obj = object()
print(obj)
  1. print(*objects, sep, end, file, flush) 高级用法
python 复制代码
print("Hello", "World", sep="-", end="!")  # Hello-World!
  1. property() 创建只读属性
python 复制代码
class Person:
    def __init__(self, name):
        self._name = name
    @property
    def name(self):
        return self._namep = Person("Alice")
print(p.name)  # Alice
  1. repr() 返回字符串表示
python 复制代码
print(repr("Hello\nWorld"))  # 'Hello\nWorld'
  1. round() 四舍五入
python 复制代码
print(round(4.567, 2))  # 4.57
  1. set() 创建集合
python 复制代码
s = set([1, 2, 3, 3])
print(s)  # {1, 2, 3}
  1. setattr() 设置对象属性
python 复制代码
class Person:
    pass
p = Person()
setattr(p, "age", 30)
print(p.age)  # 30
  1. slice() 创建切片对象
python 复制代码
lst = [10, 20, 30, 40]
s = slice(1, 3)
print(lst[s])  # [20, 30]
  1. sorted() 排序
python 复制代码
print(sorted([3, 1, 4, 2]))  # [1, 2, 3, 4]
  1. staticmethod() 定义静态方法
python 复制代码
class Math:
    @staticmethod
    def add(x, y):
        return x + yprint(Math.add(3, 4))  # 7
  1. sum() 计算总和
python 复制代码
print(sum([1, 2, 3, 4]))  # 10
  1. super() 调用父类方法
python 复制代码
class Parent:
    def greet(self):
        print("Hello from Parent")
class Child(Parent):
    def greet(self):
        super().greet()
        print("Hello from Child")
c = Child()
c.greet()
  1. tuple() 创建元组
python 复制代码
print(tuple([1, 2, 3]))  # (1, 2, 3)
  1. type() 获取对象类型
python 复制代码
print(type(123))  # <class 'int'>
  1. vars() 获取对象属性字典
python 复制代码
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = agep = Person("Alice", 25)
print(vars(p))  # {'name': 'Alice', 'age': 25}
  1. zip() 压缩多个可迭代对象
python 复制代码
names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages)))  # [('Alice', 25), ('Bob', 30)]
  1. callable() 检测对象是否可调用
python 复制代码
def foo():
    pass
print(callable(foo))  # True
  1. bin() 转换为二进制
python 复制代码
print(bin(10))  # '0b1010'
  1. hex() 转换为十六进制
python 复制代码
print(hex(255))  # '0xff'
  1. oct() 转换为八进制
python 复制代码
print(oct(8))  # '0o10'
相关推荐
追风赶月、12 分钟前
【QT】认识QT
开发语言·qt
Hockor33 分钟前
写给前端的 Python 教程三(字符串驻留和小整数池)
前端·后端·python
网安小张36 分钟前
解锁FastAPI与MongoDB聚合管道的性能奥秘
数据库·python·django
GeekAGI36 分钟前
Python 定时器框架
python
秋田君1 小时前
深入理解JavaScript设计模式之闭包与高阶函数
开发语言·javascript·设计模式
KENYCHEN奉孝1 小时前
Pandas和Django的示例Demo
python·django·pandas
拾零吖1 小时前
《Pytorch深度学习实践》ch8-多分类
人工智能·pytorch·python
亿牛云爬虫专家1 小时前
NLP驱动网页数据分类与抽取实战
python·分类·爬虫代理·电商·代理ip·网页数据·www.goofish.com
weixin_466485111 小时前
PyCharm中运行.py脚本程序
ide·python·pycharm
蜘蛛侠..1 小时前
Java中的阻塞队列
java·开发语言·优先级队列·阻塞队列·无界队列·有界队列·数组结构