Python 100个常用函数全面解析

Python 提供了许多内置函数和库函数,这些函数使得开发过程更加高效。下面我们将对 Python 中常用的 100 个函数进行详细解析,帮助大家快速掌握 Python 编程中的常用技能。


1. abs(x)

功能:返回数值 x 的绝对值。

print(abs(-5))  # 输出 5

2. all(iterable)

功能:如果给定的可迭代对象中所有元素都为真(或可迭代对象为空),则返回 True,否则返回 False

print(all([True, True, False]))  # 输出 False

3. any(iterable)

功能:如果给定的可迭代对象中至少有一个元素为真,则返回 True,否则返回 False

print(any([False, False, True]))  # 输出 True

4. bin(x)

功能:将整数 x 转换为二进制字符串。

print(bin(10))  # 输出 '0b1010'

5. bool(x)

功能:将 x 转换为布尔值 True 或 False

print(bool(1))  # 输出 True
print(bool(0))  # 输出 False

6. bytearray([source[, encoding[, errors]]])

功能:返回一个字节数组对象。

print(bytearray("Hello", "utf-8"))  # 输出 bytearray(b'Hello')

7. bytes([source[, encoding[, errors]]])

功能:返回一个不可变的字节对象。

print(bytes("Hello", "utf-8"))  # 输出 b'Hello'

8. callable(obj)

功能:检查对象 obj 是否可以被调用(即是否是一个函数、方法、类等)。

print(callable(len))  # 输出 True
print(callable(5))    # 输出 False

9. chr(i)

功能:返回整数 i 对应的字符。

print(chr(97))  # 输出 'a'

10. classmethod(function)

功能:将一个函数转换为类方法。

class MyClass:
    @classmethod
    def greet(cls):
        print("Hello from class method")

11. compile(source, filename, mode)

功能:将源码编译为代码对象。

code = compile("print('Hello, World!')", "<string>", "exec")
exec(code)  # 输出 Hello, World!

12. complex([real[, imag]])

功能:返回一个复数。

print(complex(2, 3))  # 输出 (2+3j)

13. delattr(obj, name)

功能:删除对象 obj 的属性 name

class MyClass:
    a = 5
delattr(MyClass, 'a')

14. dict([iterable])

功能:将可迭代对象转换为字典。

print(dict([("a", 1), ("b", 2)]))  # 输出 {'a': 1, 'b': 2}

15. dir([obj])

功能:返回对象的属性和方法列表。

print(dir())  # 输出当前作用域的所有名称

16. divmod(a, b)

功能:返回除法的商和余数。

print(divmod(9, 4))  # 输出 (2, 1)

17. enumerate(iterable, start=0)

功能:将一个可迭代对象组合为一个索引序列,返回 (index, value) 对。

for idx, val in enumerate(['a', 'b', 'c']):
    print(idx, val)

18. eval(expression, globals=None, locals=None)

功能:执行一个字符串表达式,并返回表达式的结果。

print(eval("3 + 5"))  # 输出 8

19. exec(object, globals=None, locals=None)

功能:执行一个动态创建的 Python 代码字符串。

exec('x = 5')
print(x)  # 输出 5

20. filter(function, iterable)

功能:筛选出可迭代对象中符合条件的元素。

print(list(filter(lambda x: x > 0, [-1, 2, 3, -4])))  # 输出 [2, 3]

21. float(x)

功能:将 x 转换为浮点数。

print(float("3.14"))  # 输出 3.14

22. format(value, format_spec)

功能:格式化字符串,类似于 str.format() 方法。

print(format(1234, "05d"))  # 输出 '01234'

23. frozenset([iterable])

功能:返回一个不可变的集合。

print(frozenset([1, 2, 3]))  # 输出 frozenset({1, 2, 3})

24. getattr(obj, name[, default])

功能:返回对象 obj 的属性 name,如果没有该属性,则返回 default

class MyClass:
    x = 5
print(getattr(MyClass, 'x'))  # 输出 5

25. globals()

功能:返回当前模块的全局变量字典。

print(globals())  # 输出当前全局变量

26. hasattr(obj, name)

功能:检查对象 obj 是否有属性 name

class MyClass:
    x = 5
print(hasattr(MyClass, 'x'))  # 输出 True

27. hash(x)

功能:返回对象 x 的哈希值。

print(hash("hello"))  # 输出字符串的哈希值

28. help([obj])

功能:提供帮助文档。如果没有传入对象,则显示 Python 的帮助信息。

help(str)  # 输出 str 类的帮助文档

29. hex(x)

功能:将整数 x 转换为十六进制字符串。

print(hex(255))  # 输出 '0xff'

30. id(obj)

功能:返回对象 obj 的唯一标识符(内存地址)。

print(id("hello"))  # 输出对象的内存地址

31. input([prompt])

功能:从控制台获取用户输入。

name = input("Enter your name: ")
print(name)

32. int(x, base=10)

功能:将 x 转换为整数。

print(int("10"))  # 输出 10

33. isinstance(obj, classinfo)

功能:检查对象 obj 是否是 classinfo 类或其子类的实例。

print(isinstance(5, int))  # 输出 True

34. issubclass(class, classinfo)

功能:检查类 class 是否是 classinfo 类的子类。

print(issubclass(bool, int))  # 输出 True

35. iter(iterable)

功能:返回一个迭代器。

it = iter([1, 2, 3])
print(next(it))  # 输出 1

36. len(s)

功能:返回对象(如字符串、列表、元组等)的长度。

print(len("Hello"))  # 输出 5

37. list([iterable])

功能:将可迭代对象转换为列表。

print(list("hello"))  # 输出 ['h', 'e', 'l', 'l', 'o']

38. locals()

功能

:返回当前局部作用域的变量字典。

x = 5
print(locals())  # 输出当前局部变量

39. map(function, iterable)

功能:对可迭代对象的每个元素应用给定的函数。

print(list(map(str, [1, 2, 3])))  # 输出 ['1', '2', '3']

40. max(iterable, *[, key, default])

功能:返回可迭代对象中的最大值。

print(max([1, 2, 3]))  # 输出 3

41. memoryview(obj)

功能:返回一个内存视图对象,可以通过它访问对象的内存数据。

mv = memoryview(b"Hello")
print(mv[0])  # 输出 72

42. min(iterable, *[, key, default])

功能:返回可迭代对象中的最小值。

print(min([1, 2, 3]))  # 输出 1

43. next(iterator[, default])

功能:返回迭代器的下一个元素。如果没有元素,返回 default

it = iter([1, 2, 3])
print(next(it))  # 输出 1

44. object()

功能:返回一个新的空对象。

obj = object()
print(obj)  # 输出 <object object at 0x...>

45. oct(x)

功能:将整数 x 转换为八进制字符串。

print(oct(8))  # 输出 '0o10'

46. open(file, mode='r', buffering=-1, encoding=None)

功能:打开一个文件并返回文件对象。

f = open('test.txt', 'w')
f.write("Hello, world!")
f.close()

47. ord(c)

功能:返回字符 c 的 Unicode 码点。

print(ord('a'))  # 输出 97

48. pow(x, y[, z])

功能:返回 x 的 y 次方。如果提供了 z,则返回 x**y % z

print(pow(2, 3))  # 输出 8

49. print(*objects, sep=' ', end='\n', file=sys.stdout)

功能:打印对象到标准输出。

print("Hello", "World", sep="-")  # 输出 Hello-World

50. property(fget=None, fset=None, fdel=None, doc=None)

功能:返回一个属性值(用于类中的属性定义)。

class MyClass:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

obj = MyClass(10)
print(obj.value)  # 输出 10

继续解析 Python 常用的函数:


51. range([start], stop[, step])

功能:返回一个指定范围内的整数序列(不包含 stop)。

print(list(range(5)))  # 输出 [0, 1, 2, 3, 4]
print(list(range(1, 6)))  # 输出 [1, 2, 3, 4, 5]
print(list(range(0, 10, 2)))  # 输出 [0, 2, 4, 6, 8]

52. repr(obj)

功能:返回对象的字符串表示形式,通常可以用来重新创建该对象。

print(repr('hello'))  # 输出 "'hello'"

53. reversed(seq)

功能:返回一个反转的迭代器。

print(list(reversed([1, 2, 3])))  # 输出 [3, 2, 1]

54. round(number[, ndigits])

功能:返回四舍五入后的数字,默认保留到小数点后两位。

print(round(3.14159, 2))  # 输出 3.14
print(round(3.14159))  # 输出 3

55. set([iterable])

功能:返回一个集合,集合是一个无序不重复的元素集。

print(set([1, 2, 2, 3]))  # 输出 {1, 2, 3}

56. setattr(obj, name, value)

功能:设置对象 obj 的属性 name 为 value

class MyClass:
    pass

obj = MyClass()
setattr(obj, 'x', 5)
print(obj.x)  # 输出 5

57. slice(start, stop[, step])

功能:返回一个 slice 对象,可以用于切片操作。

s = slice(0, 5, 2)
print("hello world"[s])  # 输出 'hlo'

58. sorted(iterable, *, key=None, reverse=False)

功能:返回一个新的排好序的列表。

print(sorted([3, 1, 2]))  # 输出 [1, 2, 3]
print(sorted([3, 1, 2], reverse=True))  # 输出 [3, 2, 1]

59. staticmethod(function)

功能:将函数转换为静态方法。

class MyClass:
    @staticmethod
    def greet():
        print("Hello, world!")
        
MyClass.greet()  # 输出 Hello, world!

60. str([object])

功能:将对象转换为字符串。

print(str(123))  # 输出 '123'

61. sum(iterable, /, start=0)

功能:返回可迭代对象中所有元素的和,start 是初始值。

print(sum([1, 2, 3]))  # 输出 6
print(sum([1, 2, 3], 10))  # 输出 16

62. super([type[, object-or-type]])

功能:返回当前类的父类或父类方法的代理。

class A:
    def hello(self):
        print("Hello from A")

class B(A):
    def hello(self):
        super().hello()
        print("Hello from B")

b = B()
b.hello()
# 输出
# Hello from A
# Hello from B

63. tuple([iterable])

功能:将可迭代对象转换为元组。

print(tuple([1, 2, 3]))  # 输出 (1, 2, 3)

64. type(obj)

功能:返回对象的类型。

print(type(5))  # 输出 <class 'int'>
print(type("Hello"))  # 输出 <class 'str'>

65. vars([object])

功能:返回对象 object 的 __dict__ 属性,表示对象的属性和方法字典。

class MyClass:
    x = 5

obj = MyClass()
print(vars(obj))  # 输出 {'x': 5}

66. zip(*iterables)

功能:将多个可迭代对象“压缩”成一个元组的迭代器。

print(list(zip([1, 2], ['a', 'b'])))  # 输出 [(1, 'a'), (2, 'b')]

67. __import__(name, globals=None, locals=None, fromlist=(), level=0)

功能:用于动态导入模块(通常不常直接使用)。

math = __import__("math")
print(math.sqrt(16))  # 输出 4.0

68. format_map(mapping)

功能:与 str.format() 类似,mapping 是一个字典,用于替换字符串中的占位符。

text = "Hello, {name}!"
print(text.format_map({"name": "Alice"}))  # 输出 'Hello, Alice!'

69. frozenset([iterable])

功能:返回一个不可变的集合。

frozen = frozenset([1, 2, 3])
print(frozen)  # 输出 frozenset({1, 2, 3})

70. hash(obj)

功能:返回对象 obj 的哈希值,用于字典查找和集合去重。

print(hash("hello"))  # 输出对应字符串的哈希值

71. help([object])

功能:显示对象的帮助信息。

help(str)  # 输出字符串类型的帮助文档

72. import(name)

功能:导入模块。

import math
print(math.sqrt(16))  # 输出 4.0

73. int(x, base=10)

功能:将 x 转换为整数。

print(int("10"))  # 输出 10
print(int("101", 2))  # 输出 5

74. input([prompt])

功能:接收用户的输入。

name = input("Enter your name: ")
print(f"Hello, {name}!")

75. isinstance(obj, class)

功能:检查对象是否是某个类的实例。

print(isinstance(10, int))  # 输出 True

76. issubclass(class, classinfo)

功能:检查类是否是某个父类的子类。

print(issubclass(bool, int))  # 输出 True

77. iter(iterable)

功能:返回可迭代对象的迭代器。

it = iter([1, 2, 3])
print(next(it))  # 输出 1

78. len(obj)

功能:返回对象的长度。

print(len("hello"))  # 输出 5
print(len([1, 2, 3]))  # 输出 3

79. locals()

功能:返回当前局部变量的字典。

a = 10
print(locals())  # 输出 {'a': 10}

80. map(function, iterable)

功能:将函数 function 应用到可迭代对象 iterable 的每个元素。

print(list(map(str, [1, 2, 3])))  # 输出 ['1', '2', '3']

81. max(iterable, *[, key, default])

功能:返回可迭代对象中的最大值。

print(max([1, 2, 3]))  # 输出 3

82. memoryview(obj)

功能:返回一个内存视图对象,用于高效访问内存数据。

mv = memoryview(b"Hello")
print(mv[0])  # 输出 72

83. min(iterable, *[, key, default])

功能:返回可迭代对象中的最小值。

print(min([1, 2, 3]))  # 输出 1

84. next(iterator[, default])

功能:返回迭代器的下一个元素。

it = iter([1, 2, 3])
print(next(it))  # 输出 1

85. object()

功能:返回一个空对象。

obj = object()
print(obj)  # 输出 <object object at 0x...>

86. open(file, mode='r', buffering=-1, encoding=None)

功能:打开一个文件并返回文件对象。

f = open('test.txt', 'w')
f.write("Hello, world!")
f.close()

87. ord(c)

功能:返回字符的 Unicode 码点。

print(ord('A'))  # 输出 65

88. pow(x, y[, z])

功能:返回 x 的 y 次方,如果提供了 z,返回 x**y % z

print(pow(2, 3))  # 输出 8

89. print(*objects, sep=' ', end='\n', file=sys.stdout)

功能:打印输出多个对象。

print("Hello", "World", sep="-")  # 输出 Hello-World

90. property(fget=None, fset=None, fdel=None, doc=None)

功能:返回一个属性值(通常用于类中的属性定义)。

class MyClass:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

obj = MyClass(10)
print(obj.value)  # 输出 10

91. reversed(seq)

功能:返回反转后的可迭代对象。

print(list(reversed([1, 2, 3])))  # 输出 [3, 2, 1]

92. round(number[, ndigits])

功能:返回四舍五入后的数值。

print(round(3.14159, 2))  # 输出 3.14

93. set([iterable])

功能:返回一个集合(无重复元素)。

print(set([1, 2, 2, 3]))  # 输出 {1, 2, 3}

94. setattr(obj, name, value)

功能:设置对象的属性值。

class MyClass:
    pass

obj = MyClass()
setattr(obj, 'x', 5)
print(obj.x)  # 输出 5

95. slice(start, stop[, step])

功能:创建一个切片对象。

s = slice(0, 5, 2)
print("hello world"[s])  # 输出 'hlo'

96. sorted(iterable, *, key=None, reverse=False)

功能:返回排好序的列表。

print(sorted([3, 1, 2]))  # 输出 [1, 2, 3]

97. staticmethod(function)

功能:将函数转换为静态方法。

class MyClass:
    @staticmethod
    def greet():
        print("Hello!")
MyClass.greet()  # 输出 Hello!

98. str([object])

功能:将对象转换为字符串。

print(str(123))  # 输出 '123'

99. sum(iterable, /, start=0)

功能:返回可迭代对象的元素总和。

print(sum([1, 2, 3]))  # 输出 6

100. super([type[, object-or-type]])

功能:返回父类的实例或方法。

class A:
    def hello(self):
        print("Hello from A")

class B(A):
    def hello(self):
        super().hello()
        print("Hello from B")

b = B()
b.hello()
# 输出:
# Hello from A
# Hello from B

以上是 Python 中 100 个常用函数的解析,这些函数涵盖了 Python 的基本数据类型操作、文件操作、类操作、函数操作等多个方面。掌握这些函数能够大大提高你在开发中的效率和代码质量。