Python常用内置函数

1 minute read

Python 内置函数(Built-in Functions)非常多,这里分类列举一些最常用的,并简要说明:


一、基础类型转换

  1. int()float()str()bool()
    将数据转换为整型、浮点型、字符串、布尔型。

    int("42")  # 42
    str(3.14)  # "3.14"
    bool(0)    # False
    
  2. list()tuple()set()dict()
    转换为列表、元组、集合、字典。

    list("abc")       # ['a', 'b', 'c']
    tuple([1, 2])     # (1, 2)
    set([1, 1, 2])    # {1, 2}
    dict([('a', 1)])  # {'a': 1}
    
  3. chr()ord()
    字符与 ASCII/Unicode 码转换。

    chr(65)  # 'A'
    ord('A') # 65
    

二、数学运算

  1. abs()
    绝对值。

    abs(-5)  # 5
    
  2. round()
    四舍五入。

    round(3.14159, 2)  # 3.14
    
  3. max()min()sum()
    最大值、最小值、求和。

    max([3, 1, 4])  # 4
    sum([1, 2, 3])  # 6
    
  4. divmod()
    同时返回商和余数。

    divmod(10, 3)  # (3, 1)
    
  5. pow()
    幂运算。

    pow(2, 3)  # 8
    

三、迭代与序列操作

  1. len()
    返回长度。

    len("hello")  # 5
    
  2. range()
    生成整数序列。

    list(range(3))  # [0, 1, 2]
    
  3. enumerate()
    为可迭代对象添加索引。

    list(enumerate(["a", "b"]))  # [(0, 'a'), (1, 'b')]
    
  4. zip()
    将多个可迭代对象”压缩”成元组对。

    list(zip([1, 2], ['a', 'b']))  # [(1, 'a'), (2, 'b')]
    
  5. reversed()sorted()
    反转、排序(返回新列表)。

    sorted([3, 1, 2])      # [1, 2, 3]
    list(reversed([1,2]))  # [2, 1]
    
  6. filter()map()
    过滤与映射(常与 lambda 结合)。

    list(map(lambda x: x*2, [1,2,3]))   # [2, 4, 6]
    list(filter(lambda x: x>1, [1,2,3])) # [2, 3]
    
  7. any()all()
    判断可迭代对象中是否有任意 True / 全部为 True。

    any([False, True])  # True
    all([1, 2, 0])      # False
    

四、输入输出

  1. print()
    打印输出。

    print("Hello", end=" ")
    
  2. input()
    从标准输入读取字符串。

    name = input("Enter name: ")
    
  3. open()
    打开文件,返回文件对象。

    with open("file.txt") as f:
        content = f.read()
    

五、其他常用

  1. type()
    返回对象类型。

    type([])  # <class 'list'>
    
  2. isinstance()
    判断对象是否为某个类(或子类)的实例。

    isinstance(3, int)  # True
    
  3. id()
    返回对象的内存地址(唯一标识)。

    id(obj)
    
  4. hasattr()getattr()setattr()
    动态操作对象属性。

    hasattr(obj, 'x')
    getattr(obj, 'x', default)
    
  5. callable()
    判断对象是否可调用(函数、类等)。

    callable(print)  # True
    
  6. help()dir()
    查看帮助、属性列表。

    help(str)   # 查看 str 的文档
    dir([])     # 查看列表的方法
    
  7. eval()exec()
    执行字符串中的代码(慎用,有安全风险)。

    eval("2+2")           # 4
    exec("a = 1 + 1")
    

六、常用内置函数速查表(按字母顺序)

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

总结:

以上是Python中一些常用的内置函数,涵盖了数学运算、类型转换、序列操作、输入输出、对象操作等多个方面。这些函数是Python编程的基础,熟练掌握能提高开发效率。注意,Python还有更多内置函数,建议查阅官方文档获取完整列表和详细信息。

  • 查看所有内置函数:print(dir(__builtins__))
  • 查看具体函数的文档:help(函数名)print(函数名.__doc__)
  • 官方完整列表:
    Python Built-in Functions

根据你的使用场景,这些函数中 print()len()str()list()range()enumerate()zip()map()filter()sorted() 等是日常编码中最常用的。