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

打印 上一主题 下一主题

主题 1490|帖子 1490|积分 4470

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Python 内置函数提供了强盛的工具,涵盖数据处置处罚、数学运算、迭代控制、范例转换等。本文总结了 100 个常用内置函数,并配备示例代码,提高编程效率。
1. abs() 取绝对值
  1. print(abs(-10))  # 10
复制代码
2. all() 判断所有元素是否为真
  1. print(all([True, 1, "hello"]))  # True
  2. print(all([True, 0, "hello"]))  # False
复制代码
3. any() 判断任意元素是否为真
  1. print(any([False, 0, "", None]))  # False
  2. print(any([False, 1, ""]))  # True
复制代码
4. ascii() 返回对象的 ASCII 表示
  1. print(ascii("你好"))  # '\u4f60\u597d'
复制代码
5. bin() 十进制转二进制
  1. print(bin(10))  # '0b1010'
复制代码
6. bool() 转换为布尔值
  1. print(bool([]))  # False
  2. print(bool(1))  # True
复制代码
7. bytearray() 创建字节数组
  1. ba = bytearray([65, 66, 67])
  2. print(ba)  # bytearray(b'ABC')
复制代码
8. bytes() 创建不可变字节序列
  1. b = bytes("hello", encoding="utf-8")
  2. print(b)  # b'hello'
复制代码
9. callable() 判断对象是否可调用
  1. def func(): pass
  2. print(callable(func))  # True
  3. print(callable(10))  # False
复制代码
10. chr() 获取 Unicode 码对应的字符
  1. print(chr(97))  # 'a'
复制代码
11. ord() 获取字符的 Unicode 编码
  1. print(ord('a'))  # 97
复制代码
12. complex() 创建复数
  1. print(complex(1, 2))  # (1+2j)
复制代码
13. dict() 创建字典
  1. d = dict(name="Alice", age=25)
  2. print(d)  # {'name': 'Alice', 'age': 25}
复制代码
14. dir() 获取对象所有属性和方法
  1. print(dir([]))  # ['append', 'clear', 'copy', ...]
复制代码
15. divmod() 取商和余数
  1. print(divmod(10, 3))  # (3, 1)
复制代码
16. enumerate() 生成索引和值
  1. lst = ["a", "b", "c"]
  2. for i, v in enumerate(lst):
  3.     print(i, v)
复制代码
17. eval() 盘算字符串表达式
  1. expr = "3 + 4"
  2. print(eval(expr))  # 7
复制代码
18. filter() 过滤序列
  1. nums = [1, 2, 3, 4, 5]
  2. even_nums = list(filter(lambda x: x % 2 == 0, nums))
  3. print(even_nums)  # [2, 4]
复制代码
19. float() 转换为浮点数
  1. print(float("3.14"))  # 3.14
复制代码
20. format() 格式化字符串
  1. print(format(10000, ","))  # '10,000'
  2. 21. frozenset() 创建不可变集合
  3. fs = frozenset([1, 2, 3])
  4. print(fs)
复制代码
22. globals() 获取全局变量
  1. print(globals())
复制代码
23. hasattr() 查抄对象是否有属性
  1. class Person:
  2.     name = "Alice"print(hasattr(Person, "name"))  # True
复制代码
24. hash() 获取哈希值
  1. print(hash("hello"))  
复制代码
25. help() 检察帮助
  1. help(print)
复制代码
26. hex() 十进制转十六进制
  1. print(hex(255))  # '0xff'
复制代码
27. id() 获取对象的唯一标识符
  1. a = 10
  2. print(id(a))
复制代码
28. input() 获取用户输入
  1. name = input("请输入你的名字: ")
  2. print("你好, " + name)
复制代码
29. int() 转换为整数
  1. print(int("123"))  # 123
复制代码
30. isinstance() 查抄对象范例
  1. print(isinstance(123, int))  # True
复制代码
31. issubclass() 查抄是否是子类
  1. class A: pass
  2. class B(A): pass
  3. print(issubclass(B, A))  # True
复制代码
32. iter() 获取迭代器
  1. lst = [1, 2, 3]
  2. it = iter(lst)
  3. print(next(it))  # 1
复制代码
33. len() 获取长度
  1. print(len([1, 2, 3]))  # 3
复制代码
34. list() 创建列表
  1. print(list("hello"))  # ['h', 'e', 'l', 'l', 'o']
复制代码
35. locals() 获取局部变量
  1. def func():
  2.     a = 10
  3.     print(locals())
  4. func()
复制代码
36. map() 对序列中的每个元素进行操作
  1. nums = [1, 2, 3, 4]
  2. squared = list(map(lambda x: x ** 2, nums))
  3. print(squared)  # [1, 4, 9, 16]
复制代码
37. max() 返回最大值
  1. print(max([10, 20, 5]))  # 20
  2. print(max("python"))  # 'y'
复制代码
38. min() 返回最小值
  1. print(min([10, 20, 5]))  # 5
  2. print(min("python"))  # 'h'
复制代码
39. next() 获取迭代器的下一个元素
  1. it = iter([10, 20, 30])
  2. print(next(it))  # 10
  3. print(next(it))  # 20
复制代码
40. object() 创建一个新对象
  1. obj = object()
  2. print(obj)  # <object object at 0x...>
复制代码
41. oct() 十进制转八进制
  1. print(oct(10))  # '0o12'
复制代码
42. open() 打开文件
  1. with open("test.txt", "w") as f:
  2.     f.write("Hello, Python!")
复制代码
43. pow() 盘算指数幂
  1. print(pow(2, 3))  # 8
  2. print(pow(2, 3, 5))  # (2^3) % 5 = 3
复制代码
44. print() 打印输出
  1. print("Hello", "Python", sep="-")  # Hello-Python
复制代码
45. range() 生成范围序列
  1. print(list(range(1, 10, 2)))  # [1, 3, 5, 7, 9]
复制代码
46. repr() 返回对象的字符串表示
  1. print(repr("Hello\nWorld"))  # "'Hello\\nWorld'"
复制代码
47. reversed() 反转序列
  1. print(list(reversed([1, 2, 3, 4])))  # [4, 3, 2, 1]
复制代码
48. round() 四舍五入
  1. print(round(3.14159, 2))  # 3.14
复制代码
49. set() 创建集合
  1. print(set([1, 2, 2, 3]))  # {1, 2, 3}
复制代码
50. setattr() 设置对象属性
  1. class Person:
  2.     pass
  3. p = Person()
  4. setattr(p, "age", 25)
  5. print(p.age)  # 25
复制代码
51. slice() 创建切片对象
  1. lst = [10, 20, 30, 40]
  2. s = slice(1, 3)
  3. print(lst[s])  # [20, 30]
复制代码
52. sorted() 排序
  1. print(sorted([3, 1, 4, 2]))  # [1, 2, 3, 4]
  2. print(sorted("python"))  # ['h', 'n', 'o', 'p', 't', 'y']
复制代码
53. staticmethod() 定义静态方法
  1. class Math:
  2.     @staticmethod
  3.     def add(x, y):
  4.         return x + yprint(Math.add(3, 4))  # 7
复制代码
54. str() 转换为字符串
  1. print(str(123))  # '123'
  2. print(str([1, 2, 3]))  # '[1, 2, 3]'
复制代码
55. sum() 盘算总和
  1. print(sum([1, 2, 3, 4]))  # 10
复制代码
56. super() 调用父类方法
  1. class Parent:
  2.     def greet(self):
  3.         print("Hello from Parent")
  4. class Child(Parent):
  5.     def greet(self):
  6.         super().greet()
  7.         print("Hello from Child")
  8. c = Child()
  9. c.greet()
复制代码
57. tuple() 创建元组
  1. print(tuple([1, 2, 3]))  # (1, 2, 3)
复制代码
58. type() 获取对象范例
  1. print(type(123))  # <class 'int'>
复制代码
59. vars() 获取对象的 __dict__ 属性
  1. class Person:
  2.     def __init__(self, name, age):
  3.         self.name = name
  4.         self.age = agep = Person("Alice", 25)
  5. print(vars(p))  # {'name': 'Alice', 'age': 25}
复制代码
60. zip() 合并多个可迭代对象
  1. names = ["Alice", "Bob"]
  2. ages = [25, 30]
  3. print(list(zip(names, ages)))  # [('Alice', 25), ('Bob', 30)]
复制代码
61. __import__() 动态导入模块
  1. math_module = __import__("math")
  2. print(math_module.sqrt(16))  # 4.0
复制代码
62. delattr() 删除对象的属性
  1. class Person:
  2.     age = 25
  3. delattr(Person, "age")
  4. print(hasattr(Person, "age"))  # False
复制代码
63. exec() 实验字符串代码
  1. code = "x = 10\ny = 20\nprint(x + y)"
  2. exec(code)  # 30
复制代码
64. memoryview() 创建内存视图对象
  1. b = bytearray("hello", "utf-8")
  2. mv = memoryview(b)
  3. print(mv[0])  # 104
复制代码
65. round() 取整
  1. print(round(4.567, 2))  # 4.57
复制代码
66. breakpoint() 设置调试断点
  1. x = 10
  2. breakpoint()  # 进入调试模式
  3. print(x)
复制代码
67. classmethod() 定义类方法
  1. class Person:
  2.     name = "Unknown"
  3.     @classmethod
  4.     def set_name(cls, name):
  5.         cls.name = namePerson.set_name("Alice")
  6. print(Person.name)  # Alice
复制代码
68. compile() 编译字符串为代码对象
  1. code = "print('Hello, World!')"
  2. compiled_code = compile(code, '<string>', 'exec')
  3. exec(compiled_code)  # Hello, World!
复制代码
69. complex() 创建复数
  1. c = complex(3, 4)
  2. print(c)  # (3+4j)
复制代码
70. del 删除对象
  1. x = 10
  2. del x
  3. # print(x)  # NameError: name 'x' is not defined
复制代码
71. ellipsis 省略号对象
  1. def func():
  2.     ...
  3. print(func())  # None
复制代码
72. float.fromhex() 将十六进制转换为浮点数
  1. print(float.fromhex('0x1.8p3'))  # 12.0
复制代码
73. format_map() 利用映射对象格式化字符串
  1. class Person:
  2.     age = 25
  3. print(getattr(Person, "age"))  # 25
复制代码
74. getattr() 获取对象属性
  1. class Person:
  2.     age = 25
  3. print(getattr(Person, "age"))  # 25
复制代码
75. is 判断是否是同一个对象
  1. a = [1, 2, 3]
  2. b = a
  3. print(a is b)  # True
复制代码
76. issubclass() 判断是否是子类
  1. class A: pass
  2. class B(A): pass
  3. print(issubclass(B, A))  # True
复制代码
77. iter() 创建迭代器
  1. lst = [1, 2, 3]
  2. it = iter(lst)
  3. print(next(it))  # 1
复制代码
78. len() 获取长度
  1. print(len([1, 2, 3]))  # 3
复制代码
79. memoryview() 创建内存视图
  1. b = bytearray("hello", "utf-8")
  2. mv = memoryview(b)
  3. print(mv[0])  # 104
复制代码
80. object() 创建基础对象
  1. obj = object()
  2. print(obj)
复制代码
81. print(*objects, sep, end, file, flush) 高级用法
  1. print("Hello", "World", sep="-", end="!")  # Hello-World!
复制代码
82. property() 创建只读属性
  1. class Person:
  2.     def __init__(self, name):
  3.         self._name = name
  4.     @property
  5.     def name(self):
  6.         return self._namep = Person("Alice")
  7. print(p.name)  # Alice
复制代码
83. repr() 返回字符串表示
  1. print(repr("Hello\nWorld"))  # 'Hello\nWorld'
复制代码
84. round() 四舍五入
  1. print(round(4.567, 2))  # 4.57
复制代码
85. set() 创建集合
  1. s = set([1, 2, 3, 3])
  2. print(s)  # {1, 2, 3}
复制代码
86. setattr() 设置对象属性
  1. class Person:
  2.     pass
  3. p = Person()
  4. setattr(p, "age", 30)
  5. print(p.age)  # 30
复制代码
87. slice() 创建切片对象
  1. lst = [10, 20, 30, 40]
  2. s = slice(1, 3)
  3. print(lst[s])  # [20, 30]
复制代码
88. sorted() 排序
  1. print(sorted([3, 1, 4, 2]))  # [1, 2, 3, 4]
复制代码
89. staticmethod() 定义静态方法
  1. class Math:
  2.     @staticmethod
  3.     def add(x, y):
  4.         return x + yprint(Math.add(3, 4))  # 7
复制代码
90. sum() 盘算总和
  1. print(sum([1, 2, 3, 4]))  # 10
复制代码
91. super() 调用父类方法
  1. class Parent:
  2.     def greet(self):
  3.         print("Hello from Parent")
  4. class Child(Parent):
  5.     def greet(self):
  6.         super().greet()
  7.         print("Hello from Child")
  8. c = Child()
  9. c.greet()
复制代码
92. tuple() 创建元组
  1. print(tuple([1, 2, 3]))  # (1, 2, 3)
复制代码
93. type() 获取对象范例
  1. print(type(123))  # <class 'int'>
复制代码
94. vars() 获取对象属性字典
  1. class Person:
  2.     def __init__(self, name, age):
  3.         self.name = name
  4.         self.age = agep = Person("Alice", 25)
  5. print(vars(p))  # {'name': 'Alice', 'age': 25}
复制代码
95. zip() 压缩多个可迭代对象
  1. names = ["Alice", "Bob"]
  2. ages = [25, 30]
  3. print(list(zip(names, ages)))  # [('Alice', 25), ('Bob', 30)]
复制代码
96. callable() 检测对象是否可调用
  1. def foo():
  2.     pass
  3. print(callable(foo))  # True
复制代码
97. bin() 转换为二进制
  1. print(bin(10))  # '0b1010'
复制代码
98. hex() 转换为十六进制
  1. print(hex(255))  # '0xff'
复制代码
99. oct() 转换为八进制
  1. print(oct(8))  # '0o10'
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

梦见你的名字

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表