Python 內置函數提供了強大的工具,涵蓋數據處理、數學運算、迭代控制、類型轉換等。本文總結了 100 個常用內置函數,并配備示例代碼,提高編程效率。
1. abs() 取絕對值
print(abs(-10)) ?# 10
2. all() 判斷所有元素是否為真
print(all([True, 1, "hello"])) ?# True
print(all([True, 0, "hello"])) ?# False
3. any() 判斷任意元素是否為真
print(any([False, 0, "", None])) ?# False
print(any([False, 1, ""])) ?# True
4. ascii() 返回對象的 ASCII 表示
print(ascii("你好")) ?# '\u4f60\u597d'
5. bin() 十進制轉二進制
print(bin(10)) ?# '0b1010'
6. bool() 轉換為布爾值
print(bool([])) ?# False
print(bool(1)) ?# True
7. bytearray() 創建字節數組
ba = bytearray([65, 66, 67])
print(ba) ?# bytearray(b'ABC')
8. bytes() 創建不可變字節序列
b = bytes("hello", encoding="utf-8")
print(b) ?# b'hello'
9. callable() 判斷對象是否可調用
def func(): pass
print(callable(func)) ?# True
print(callable(10)) ?# False
10. chr() 獲取 Unicode 碼對應的字符
print(chr(97)) ?# 'a'
11. ord() 獲取字符的 Unicode 編碼
print(ord('a')) ?# 97
12. complex() 創建復數
print(complex(1, 2)) ?# (1+2j)
13. dict() 創建字典
d = dict(name="Alice", age=25)
print(d) ?# {'name': 'Alice', 'age': 25}
14. dir() 獲取對象所有屬性和方法
print(dir([])) ?# ['append', 'clear', 'copy', ...]
15. divmod() 取商和余數
print(divmod(10, 3)) ?# (3, 1)
16. enumerate() 生成索引和值
lst = ["a", "b", "c"]
for i, v in enumerate(lst):print(i, v)
17. eval() 計算字符串表達式
expr = "3 + 4"
print(eval(expr)) ?# 7
18. filter() 過濾序列
nums = [1, 2, 3, 4, 5]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums) ?# [2, 4]
19. float() 轉換為浮點數
print(float("3.14")) ?# 3.14
20. format() 格式化字符串
print(format(10000, ",")) ?# '10,000'
21. frozenset() 創建不可變集合
fs = frozenset([1, 2, 3])
print(fs)
22. globals() 獲取全局變量
print(globals())
23. hasattr() 檢查對象是否有屬性
class Person:name = "Alice"print(hasattr(Person, "name")) ?# True
24. hash() 獲取哈希值
print(hash("hello")) ?
25. help() 查看幫助
help(print)
26. hex() 十進制轉十六進制
print(hex(255)) ?# '0xff'
27. id() 獲取對象的唯一標識符
a = 10
print(id(a))
28. input() 獲取用戶輸入
name = input("請輸入你的名字: ")
print("你好, " + name)
29. int() 轉換為整數
print(int("123")) ?# 123
30. isinstance() 檢查對象類型
print(isinstance(123, int)) ?# True
31. issubclass() 檢查是否是子類
class A: pass
class B(A): pass
print(issubclass(B, A)) ?# True
32. iter() 獲取迭代器
lst = [1, 2, 3]
it = iter(lst)
print(next(it)) ?# 1
33. len() 獲取長度
print(len([1, 2, 3])) ?# 3
34. list() 創建列表
print(list("hello")) ?# ['h', 'e', 'l', 'l', 'o']
35. locals() 獲取局部變量
def func():a = 10print(locals())func()
36. map() 對序列中的每個元素進行操作
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared) ?# [1, 4, 9, 16]
37. max() 返回最大值
print(max([10, 20, 5])) ?# 20
print(max("python")) ?# 'y'
38. min() 返回最小值
print(min([10, 20, 5])) ?# 5
print(min("python")) ?# 'h'
39. next() 獲取迭代器的下一個元素
it = iter([10, 20, 30])
print(next(it)) ?# 10
print(next(it)) ?# 20
40. object() 創建一個新對象
obj = object()
print(obj) ?# <object object at 0x...>
41. oct() 十進制轉八進制
print(oct(10)) ?# '0o12'
42. open() 打開文件
with open("test.txt", "w") as f:f.write("Hello, Python!")
43. pow() 計算指數冪
print(pow(2, 3)) ?# 8
print(pow(2, 3, 5)) ?# (2^3) % 5 = 3
44. print() 打印輸出
print("Hello", "Python", sep="-") ?# Hello-Python
45. range() 生成范圍序列
print(list(range(1, 10, 2))) ?# [1, 3, 5, 7, 9]
46. repr() 返回對象的字符串表示
print(repr("Hello\nWorld")) ?# "'Hello\\nWorld'"
47. reversed() 反轉序列
print(list(reversed([1, 2, 3, 4]))) ?# [4, 3, 2, 1]
48. round() 四舍五入
print(round(3.14159, 2)) ?# 3.14
49. set() 創建集合
print(set([1, 2, 2, 3])) ?# {1, 2, 3}
50. setattr() 設置對象屬性
class Person:pass
p = Person()
setattr(p, "age", 25)
print(p.age) ?# 25
51. slice() 創建切片對象
lst = [10, 20, 30, 40]
s = slice(1, 3)
print(lst[s]) ?# [20, 30]
52. sorted() 排序
print(sorted([3, 1, 4, 2])) ?# [1, 2, 3, 4]
print(sorted("python")) ?# ['h', 'n', 'o', 'p', 't', 'y']
53. staticmethod() 定義靜態方法
class Math:@staticmethoddef add(x, y):return x + yprint(Math.add(3, 4)) ?# 7
54. str() 轉換為字符串
print(str(123)) ?# '123'
print(str([1, 2, 3])) ?# '[1, 2, 3]'
55. sum() 計算總和
print(sum([1, 2, 3, 4])) ?# 10
56. super() 調用父類方法
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()
57. tuple() 創建元組
print(tuple([1, 2, 3])) ?# (1, 2, 3)
58. type() 獲取對象類型
print(type(123)) ?# <class 'int'>
59. vars() 獲取對象的 __dict__ 屬性
class Person:def __init__(self, name, age):self.name = nameself.age = agep = Person("Alice", 25)
print(vars(p)) ?# {'name': 'Alice', 'age': 25}
60. zip() 合并多個可迭代對象
names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages))) ?# [('Alice', 25), ('Bob', 30)]
61. __import__() 動態導入模塊
math_module = __import__("math")
print(math_module.sqrt(16)) ?# 4.0
62. delattr() 刪除對象的屬性
class Person:age = 25
delattr(Person, "age")
print(hasattr(Person, "age")) ?# False
63. exec() 執行字符串代碼
code = "x = 10\ny = 20\nprint(x + y)"
exec(code) ?# 30
64. memoryview() 創建內存視圖對象
b = bytearray("hello", "utf-8")
mv = memoryview(b)
print(mv[0]) ?# 104
65. round() 取整
print(round(4.567, 2)) ?# 4.57
66. breakpoint() 設置調試斷點
x = 10
breakpoint() ?# 進入調試模式
print(x)
67. classmethod() 定義類方法
class Person:name = "Unknown"@classmethoddef set_name(cls, name):cls.name = namePerson.set_name("Alice")
print(Person.name) ?# Alice
68. compile() 編譯字符串為代碼對象
code = "print('Hello, World!')"
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code) ?# Hello, World!
69. complex() 創建復數
c = complex(3, 4)
print(c) ?# (3+4j)
70. del 刪除對象
x = 10
del x
# print(x) ?# NameError: name 'x' is not defined
71. ellipsis 省略號對象
def func():...
print(func()) ?# None
72. float.fromhex() 將十六進制轉換為浮點數
print(float.fromhex('0x1.8p3')) ?# 12.0
73. format_map() 使用映射對象格式化字符串
class Person:age = 25
print(getattr(Person, "age")) ?# 25
74. getattr() 獲取對象屬性
class Person:age = 25
print(getattr(Person, "age")) ?# 25
75. is 判斷是否是同一個對象
a = [1, 2, 3]
b = a
print(a is b) ?# True
76. issubclass() 判斷是否是子類
class A: pass
class B(A): passprint(issubclass(B, A)) ?# True
77. iter() 創建迭代器
lst = [1, 2, 3]
it = iter(lst)
print(next(it)) ?# 1
78. len() 獲取長度
print(len([1, 2, 3])) ?# 3
79. memoryview() 創建內存視圖
b = bytearray("hello", "utf-8")
mv = memoryview(b)
print(mv[0]) ?# 104
80. object() 創建基礎對象
obj = object()
print(obj)
81. print(*objects, sep, end, file, flush) 高級用法
print("Hello", "World", sep="-", end="!") ?# Hello-World!
82. property() 創建只讀屬性
class Person:def __init__(self, name):self._name = name@propertydef name(self):return self._namep = Person("Alice")
print(p.name) ?# Alice
83. repr() 返回字符串表示
print(repr("Hello\nWorld")) ?# 'Hello\nWorld'
84. round() 四舍五入
print(round(4.567, 2)) ?# 4.57
85. set() 創建集合
s = set([1, 2, 3, 3])
print(s) ?# {1, 2, 3}
86. setattr() 設置對象屬性
class Person:pass
p = Person()
setattr(p, "age", 30)
print(p.age) ?# 30
87. slice() 創建切片對象
lst = [10, 20, 30, 40]
s = slice(1, 3)
print(lst[s]) ?# [20, 30]
88. sorted() 排序
print(sorted([3, 1, 4, 2])) ?# [1, 2, 3, 4]
89. staticmethod() 定義靜態方法
class Math:@staticmethoddef add(x, y):return x + yprint(Math.add(3, 4)) ?# 7
90. sum() 計算總和
print(sum([1, 2, 3, 4])) ?# 10
91. super() 調用父類方法
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()
92. tuple() 創建元組
print(tuple([1, 2, 3])) ?# (1, 2, 3)
93. type() 獲取對象類型
print(type(123)) ?# <class 'int'>
94. vars() 獲取對象屬性字典
class Person:def __init__(self, name, age):self.name = nameself.age = agep = Person("Alice", 25)
print(vars(p)) ?# {'name': 'Alice', 'age': 25}
95. zip() 壓縮多個可迭代對象
names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages))) ?# [('Alice', 25), ('Bob', 30)]
96. callable() 檢測對象是否可調用
def foo():pass
print(callable(foo)) ?# True
97. bin() 轉換為二進制
print(bin(10)) ?# '0b1010'
98. hex() 轉換為十六進制
print(hex(255)) ?# '0xff'
99. oct() 轉換為八進制
print(oct(8)) ?# '0o10'