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

ops/2025/3/16 12:32:35/

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

1. abs() 取绝对值

python">print(abs(-10))  # 10

2. all() 判断所有元素是否为真

python">print(all([True, 1, "hello"]))  # True
print(all([True, 0, "hello"]))  # False

3. any() 判断任意元素是否为真

python">print(any([False, 0, "", None]))  # False
print(any([False, 1, ""]))  # True

4. ascii() 返回对象的 ASCII 表示

python">print(ascii("你好"))  # '\u4f60\u597d'

5. bin() 十进制转二进制

python">print(bin(10))  # '0b1010'

6. bool() 转换为布尔值

python">print(bool([]))  # False
print(bool(1))  # True

7. bytearray() 创建字节数组

python">ba = bytearray([65, 66, 67])
print(ba)  # bytearray(b'ABC')

8. bytes() 创建不可变字节序列

python">b = bytes("hello", encoding="utf-8")
print(b)  # b'hello'

9. callable() 判断对象是否可调用

python">def func(): pass
print(callable(func))  # True
print(callable(10))  # False

10. chr() 获取 Unicode 码对应的字符

python">print(chr(97))  # 'a'

11. ord() 获取字符的 Unicode 编码

python">print(ord('a'))  # 97

12. complex() 创建复数

python">print(complex(1, 2))  # (1+2j)

13. dict() 创建字典

python">d = dict(name="Alice", age=25)
print(d)  # {'name': 'Alice', 'age': 25}

14. dir() 获取对象所有属性和方法

python">print(dir([]))  # ['append', 'clear', 'copy', ...]

15. divmod() 取商和余数

python">print(divmod(10, 3))  # (3, 1)

16. enumerate() 生成索引和值

python">lst = ["a", "b", "c"]
for i, v in enumerate(lst):print(i, v)

17. eval() 计算字符串表达式

python">expr = "3 + 4"
print(eval(expr))  # 7

18. filter() 过滤序列

python">nums = [1, 2, 3, 4, 5]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
print(even_nums)  # [2, 4]

19. float() 转换为浮点数

python">print(float("3.14"))  # 3.14

20. format() 格式化字符串

python">print(format(10000, ","))  # '10,000'
21. frozenset() 创建不可变集合
fs = frozenset([1, 2, 3])
print(fs)

22. globals() 获取全局变量

python">print(globals())

23. hasattr() 检查对象是否有属性

python">class Person:name = "Alice"print(hasattr(Person, "name"))  # True

24. hash() 获取哈希值

python">print(hash("hello"))  

25. help() 查看帮助

python">help(print)

26. hex() 十进制转十六进制

python">print(hex(255))  # '0xff'

27. id() 获取对象的唯一标识符

python">a = 10
print(id(a))

28. input() 获取用户输入

python">name = input("请输入你的名字: ")
print("你好, " + name)

29. int() 转换为整数

python">print(int("123"))  # 123

30. isinstance() 检查对象类型

python">print(isinstance(123, int))  # True

31. issubclass() 检查是否是子类

python">class A: pass
class B(A): pass
print(issubclass(B, A))  # True

32. iter() 获取迭代器

python">lst = [1, 2, 3]
it = iter(lst)
print(next(it))  # 1

33. len() 获取长度

python">print(len([1, 2, 3]))  # 3

34. list() 创建列表

python">print(list("hello"))  # ['h', 'e', 'l', 'l', 'o']

35. locals() 获取局部变量

python">def func():a = 10print(locals())func()

36. map() 对序列中的每个元素进行操作

python">nums = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, nums))
print(squared)  # [1, 4, 9, 16]

37. max() 返回最大值

python">print(max([10, 20, 5]))  # 20
print(max("python"))  # 'y'

38. min() 返回最小值

python">print(min([10, 20, 5]))  # 5
print(min("python"))  # 'h'

39. next() 获取迭代器的下一个元素

python">it = iter([10, 20, 30])
print(next(it))  # 10
print(next(it))  # 20

40. object() 创建一个新对象

python">obj = object()
print(obj)  # <object object at 0x...>

41. oct() 十进制转八进制

python">print(oct(10))  # '0o12'

42. open() 打开文件

python">with open("test.txt", "w") as f:f.write("Hello, Python!")

43. pow() 计算指数幂

python">print(pow(2, 3))  # 8
print(pow(2, 3, 5))  # (2^3) % 5 = 3

44. print() 打印输出

python">print("Hello", "Python", sep="-")  # Hello-Python

45. range() 生成范围序列

python">print(list(range(1, 10, 2)))  # [1, 3, 5, 7, 9]

46. repr() 返回对象的字符串表示

python">print(repr("Hello\nWorld"))  # "'Hello\\nWorld'"

47. reversed() 反转序列

python">print(list(reversed([1, 2, 3, 4])))  # [4, 3, 2, 1]

48. round() 四舍五入

python">print(round(3.14159, 2))  # 3.14

49. set() 创建集合

python">print(set([1, 2, 2, 3]))  # {1, 2, 3}

50. setattr() 设置对象属性

python">class Person:pass
p = Person()
setattr(p, "age", 25)
print(p.age)  # 25

51. slice() 创建切片对象

python">lst = [10, 20, 30, 40]
s = slice(1, 3)
print(lst[s])  # [20, 30]

52. sorted() 排序

python">print(sorted([3, 1, 4, 2]))  # [1, 2, 3, 4]
print(sorted("python"))  # ['h', 'n', 'o', 'p', 't', 'y']

53. staticmethod() 定义静态方法

python">class Math:@staticmethoddef add(x, y):return x + yprint(Math.add(3, 4))  # 7

54. str() 转换为字符串

python">print(str(123))  # '123'
print(str([1, 2, 3]))  # '[1, 2, 3]'

55. sum() 计算总和

python">print(sum([1, 2, 3, 4]))  # 10

56. 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()

57. tuple() 创建元组

python">print(tuple([1, 2, 3]))  # (1, 2, 3)

58. type() 获取对象类型

python">print(type(123))  # <class 'int'>

59. vars() 获取对象的 __dict__ 属性

python">class Person:def __init__(self, name, age):self.name = nameself.age = agep = Person("Alice", 25)
print(vars(p))  # {'name': 'Alice', 'age': 25}

60. zip() 合并多个可迭代对象

python">names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages)))  # [('Alice', 25), ('Bob', 30)]

61. __import__() 动态导入模块

python">math_module = __import__("math")
print(math_module.sqrt(16))  # 4.0

62. delattr() 删除对象的属性

python">class Person:age = 25
delattr(Person, "age")
print(hasattr(Person, "age"))  # False

63. exec() 执行字符串代码

python">code = "x = 10\ny = 20\nprint(x + y)"
exec(code)  # 30

64. memoryview() 创建内存视图对象

python">b = bytearray("hello", "utf-8")
mv = memoryview(b)
print(mv[0])  # 104

65. round() 取整

python">print(round(4.567, 2))  # 4.57

66. breakpoint() 设置调试断点

python">x = 10
breakpoint()  # 进入调试模式
print(x)

67. classmethod() 定义类方法

python">class Person:name = "Unknown"@classmethoddef set_name(cls, name):cls.name = namePerson.set_name("Alice")
print(Person.name)  # Alice

68. compile() 编译字符串为代码对象

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

69. complex() 创建复数

python">c = complex(3, 4)
print(c)  # (3+4j)

70. del 删除对象

python">x = 10
del x
# print(x)  # NameError: name 'x' is not defined

71. ellipsis 省略号对象

python">def func():...
print(func())  # None

72. float.fromhex() 将十六进制转换为浮点数

python">print(float.fromhex('0x1.8p3'))  # 12.0

73. format_map() 使用映射对象格式化字符串

python">class Person:age = 25
print(getattr(Person, "age"))  # 25

74. getattr() 获取对象属性

python">class Person:age = 25
print(getattr(Person, "age"))  # 25

75. is 判断是否是同一个对象

python">a = [1, 2, 3]
b = a
print(a is b)  # True

76. issubclass() 判断是否是子类

python">class A: pass
class B(A): passprint(issubclass(B, A))  # True

77. iter() 创建迭代器

python">lst = [1, 2, 3]
it = iter(lst)
print(next(it))  # 1

78. len() 获取长度

python">print(len([1, 2, 3]))  # 3

79. memoryview() 创建内存视图

python">b = bytearray("hello", "utf-8")
mv = memoryview(b)
print(mv[0])  # 104

80. object() 创建基础对象

python">obj = object()
print(obj)

81. print(*objects, sep, end, file, flush) 高级用法

python">print("Hello", "World", sep="-", end="!")  # Hello-World!

82. property() 创建只读属性

python">class Person:def __init__(self, name):self._name = name@propertydef name(self):return self._namep = Person("Alice")
print(p.name)  # Alice

83. repr() 返回字符串表示

python">print(repr("Hello\nWorld"))  # 'Hello\nWorld'

84. round() 四舍五入

python">print(round(4.567, 2))  # 4.57

85. set() 创建集合

python">s = set([1, 2, 3, 3])
print(s)  # {1, 2, 3}

86. setattr() 设置对象属性

python">class Person:pass
p = Person()
setattr(p, "age", 30)
print(p.age)  # 30

87. slice() 创建切片对象

python">lst = [10, 20, 30, 40]
s = slice(1, 3)
print(lst[s])  # [20, 30]

88. sorted() 排序

python">print(sorted([3, 1, 4, 2]))  # [1, 2, 3, 4]

89. staticmethod() 定义静态方法

python">class Math:@staticmethoddef add(x, y):return x + yprint(Math.add(3, 4))  # 7

90. sum() 计算总和

python">print(sum([1, 2, 3, 4]))  # 10

91. 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()

92. tuple() 创建元组

python">print(tuple([1, 2, 3]))  # (1, 2, 3)

93. type() 获取对象类型

python">print(type(123))  # <class 'int'>

94. vars() 获取对象属性字典

python">class Person:def __init__(self, name, age):self.name = nameself.age = agep = Person("Alice", 25)
print(vars(p))  # {'name': 'Alice', 'age': 25}

95. zip() 压缩多个可迭代对象

python">names = ["Alice", "Bob"]
ages = [25, 30]
print(list(zip(names, ages)))  # [('Alice', 25), ('Bob', 30)]

96. callable() 检测对象是否可调用

python">def foo():pass
print(callable(foo))  # True

97. bin() 转换为二进制

python">print(bin(10))  # '0b1010'

98. hex() 转换为十六进制

python">print(hex(255))  # '0xff'

99. oct() 转换为八进制

python">print(oct(8))  # '0o10'

http://www.ppmy.cn/ops/166204.html

相关文章

【2025】基于python+django的慢性病健康管理系统(源码、万字文档、图文修改、调试答疑)

系统功能结构图如下 慢性病健康管理系统 课题背景 随着全球人口老龄化的加剧以及生活方式的改变&#xff0c;慢性病的发病率呈上升趋势&#xff0c;给个人健康和社会医疗资源带来了巨大压力。传统的慢性病管理模式存在信息不畅、患者参与度低、医疗资源分配不均等问题&#xf…

如何利用物理按键控制LVGL控件的大小与状态

​ lvgl可以利用物理按键控制控件的选择和状态&#xff0c;演示视频如下&#xff1a; 单物理按键控制LVGL控件的选择和状态 移植方法如下&#xff1a;1 在注册设备中&#xff0c;填写对应的变量和初始化函数。这里我们以移keypad为例&#xff0c;因为keypad的功能很多。 ![请添…

使用Fluent-bit将容器标准输入和输出的日志发送到Kafka

什么是fluent-bit&#xff1f; Fluent Bit 是一款开源的轻量级日志处理器与转发器&#xff0c;专为嵌入式系统、容器化环境及分布式架构设计。其核心功能包括日志收集、过滤、聚合和传输&#xff0c;支持多种输入源&#xff08;如文件、系统日志、HTTP接口&#xff09;和输出目…

解决电脑问题(8)——网络问题

电脑网络出现问题的原因较为复杂&#xff0c;以下是从网络连接、网络配置以及网络环境等方面的常见问题及解决方法&#xff1a; 网络连接问题 检查物理连接&#xff1a;对于有线网络&#xff0c;检查网线是否插好&#xff0c;网线有无破损、断裂等情况。对于无线网络&#xff…

每日一题---数组中两个字符串的最小距离

数组中两个字符串的最小距离 给定一个字符串数组strs&#xff0c;再给定两个字符串str1和str2&#xff0c;返回在strs中str1和str2的最小距离&#xff0c;如果str1或str2为null&#xff0c;或不在strs中&#xff0c;返回-1。 链接&#xff1a;数组中两个字符串的最小距离__牛…

GitHub 汉化插件,GitHub 中文化界面安装全教程_最新

概述 GitHub作为全球最大的代码托管平台&#xff0c;拥有庞大的用户群体。对于中文用户来说&#xff0c;如果能将GitHub界面汉化&#xff0c;将大大提高使用体验和工作效率。本文将详细介绍如何通过安装汉化插件&#xff0c;实现GitHub界面的中文化。 感谢maboloshi作者的无私奉…

【eNSP实战】三层交换机使用ACL实现网络安全

拓图 要求&#xff1a; vlan1可以访问Internetvlan2和vlan3不能访问Internet和vlan1vlan2和vlan3之间可以互相访问PC配置如图所示&#xff0c;这里不展示 LSW1接口vlan配置 vlan batch 10 20 30 # interface Vlanif1ip address 192.168.40.2 255.255.255.0 # interface Vla…

贪心算法简介(greed)

前言&#xff1a; 贪心算法&#xff08;Greedy Algorithm&#xff09;是一种在每个决策阶段都选择当前最优解的算法策略&#xff0c;通过局部最优的累积来寻求全局最优解。其本质是"短视"策略&#xff0c;不回溯已做选择。 什么是贪心、如何来理解贪心(个人对贪心的…