Python 100个函数及代码!码住(python函数编程)
wptr33 2025-07-15 01:26 3 浏览
Python内置函数是Python语言中直接可以使用的函数,不需要导入任何模块。它们提供了对基本操作的支持,如处理数据类型、执行数学运算、操作字符串等。以下是100个常见的Python函数的解释及代码示例。
1. abs()
返回数字的绝对值。
print(abs(-5)) # 输出: 5
2. all()
判断可迭代对象中的所有元素是否为True,如果是返回True,否则返回False。
print(all([1, 2, 3])) # 输出: True
print(all([1, 0, 3])) # 输出: False
3. any()
判断可迭代对象中是否有元素为True。如果有返回True,否则返回False。
print(any([0, 1, 0])) # 输出: True
print(any([0, 0, 0])) # 输出: False
4. ascii()
返回一个对象的可打印字符串表示,非ASCII字符会转义为\uXXXX格式。
print(ascii('你好')) # 输出: 'u'\u4f60\u597d''
5. bin()
将一个整数转换为二进制字符串。
print(bin(10)) # 输出: '0b1010'
6. bool()
将给定的值转换为布尔值。
print(bool(0)) # 输出: False
print(bool(1)) # 输出: True
7. bytearray()
返回一个新的字节数组对象。
print(bytearray([65, 66, 67])) # 输出: bytearray(b'ABC')
8. bytes()
返回一个新的字节对象。
print(bytes([65, 66, 67])) # 输出: b'ABC'
9. callable()
检查对象是否是可调用的(如函数或类)。
print(callable(len)) # 输出: True
print(callable(10)) # 输出: False
10. chr()
将整数转换为对应的字符。
print(chr(65)) # 输出: 'A'
11. classmethod()
返回一个类方法的实例。
class MyClass:
@classmethod
def hello(cls):
print("Hello, class!")
# 返回类方法
cls_method = classmethod(MyClass.hello)
cls_method()
12. compile()
将代码字符串编译为代码对象。
code = compile('print("Hello")', '<string>', 'exec')
exec(code) # 输出: Hello
13. complex()
创建一个复数。
print(complex(2, 3)) # 输出: (2+3j)
14. delattr()
删除对象的指定属性。
class MyClass:
x = 5
obj = MyClass()
delattr(obj, 'x')
15. dict()
创建一个字典。
print(dict(a=1, b=2)) # 输出: {'a': 1, 'b': 2}
16. dir()
返回对象的属性和方法列表。
print(dir([1, 2, 3])) # 输出: ['__add__', '__class__', '__delattr__', ..., 'pop']
17. divmod()
返回商和余数的元组。
print(divmod(9, 4)) # 输出: (2, 1)
18. enumerate()
返回一个枚举对象,包含索引和值。
for i, value in enumerate(['a', 'b', 'c']):
print(i, value)
# 输出:
# 0 a
# 1 b
# 2 c
19. eval()
执行表达式字符串并返回结果。
print(eval('3 + 5')) # 输出: 8
20. exec()
执行多行Python代码字符串。
code = """
def say_hello():
print("Hello World")
"""
exec(code)
say_hello() # 输出: Hello World
21. filter()
过滤可迭代对象的元素,返回符合条件的元素。
def is_even(x):
return x % 2 == 0
print(list(filter(is_even, [1, 2, 3, 4]))) # 输出: [2, 4]
22. float()
将对象转换为浮动小数。
print(float(3)) # 输出: 3.0
23. format()
格式化字符串。
print("Hello, {}".format("world")) # 输出: Hello, world
24. frozenset()
返回一个冻结集合。
fs = frozenset([1, 2, 3, 4])
print(fs) # 输出: frozenset({1, 2, 3, 4})
25. getattr()
返回对象的指定属性值。
class MyClass:
x = 10
obj = MyClass()
print(getattr(obj, 'x')) # 输出: 10
26. globals()
返回当前全局符号表的字典。
print(globals()) # 输出: 包含全局变量的字典
27. hasattr()
检查对象是否具有指定的属性。
class MyClass:
x = 5
obj = MyClass()
print(hasattr(obj, 'x')) # 输出: True
28. hash()
返回对象的哈希值。
print(hash('hello')) # 输出: 一个整数值
29. help()
显示对象的帮助信息。
help(str) # 输出: 显示str类的帮助信息
30. hex()
将整数转换为十六进制字符串。
print(hex(255)) # 输出: '0xff'
31. id()
返回对象的唯一标识符。
a = 10
print(id(a)) # 输出: 唯一标识符
32. input()
从用户获取输入。
name = input("What's your name? ") # 输入: John
print(f"Hello, {name}") # 输出: Hello, John
33. int()
将对象转换为整数。
print(int("10")) # 输出: 10
34. isinstance()
检查对象是否是指定类的实例。
print(isinstance(10, int)) # 输出: True
35. issubclass()
检查一个类是否是另一个类的子类。
class A: pass
class B(A): pass
print(issubclass(B, A)) # 输出: True
36. iter()
返回对象的迭代器。
lst = [1, 2, 3]
it = iter(lst)
print(next(it)) # 输出: 1
37. len()
返回对象的长度。
print(len("Hello")) # 输出: 5
38. list()
将可迭代对象转换为列表。
print(list((1, 2, 3))) # 输出: [1, 2, 3]
39. locals()
返回当前局部符号表的字典。
x = 10
print(locals()) # 输出: {'x': 10}
40. map()
将函数应用到可迭代对象的每一个元素上。
def square(x):
return x * x
print(list(map(square, [1, 2, 3]))) # 输出: [1, 4, 9]
41. max()
返回可迭代对象中的最大值。
print(max([1, 3, 2])) # 输出: 3
42. memoryview()
返回一个内存视图对象。
b = bytearray([1, 2, 3])
m = memoryview(b)
print(m[0]) # 输出: 1
43. min()
返回可迭代对象中的最小值。
print(min([1, 3, 2])) # 输出: 1
44. next()
返回可迭代对象的下一个项目。
it = iter([1, 2, 3])
print(next(it)) # 输出: 1
45. object()
返回一个新的空对象。
obj = object()
print(obj) # 输出: <object object at 0x...>
46. oct()
将整数转换为八进制字符串。
print(oct(8)) # 输出: '0o10'
47. open()
打开一个文件,并返回文件对象。
with open('test.txt', 'w') as f:
f.write("Hello")
48. ord()
将字符转换为其对应的Unicode码点。
print(ord('A')) # 输出: 65
49. pow()
返回x的y次方,如果给定第三个参数,返回x的y次方对z取模的结果。
print(pow(2, 3)) # 输出: 8
print(pow(2, 3, 5)) # 输出: 3
50. print()
打印输出内容。
print("Hello World") # 输出: Hello World
51. property()
返回属性值的管理方法。
class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
obj = MyClass(10)
print(obj.value) # 输出: 10
52. range()
生成一个整数序列。
for i in range(5):
print(i) # 输出: 0 1 2 3 4
53. repr()
返回对象的字符串表示。
print(repr("Hello")) # 输出: "'Hello'"
54. reversed()
返回一个反转的可迭代对象。
print(list(reversed([1, 2, 3]))) # 输出: [3, 2, 1]
55. round()
返回浮点数四舍五入后的值。
print(round(3.14159, 2)) # 输出: 3.14
56. set()
创建一个集合对象。
print(set([1, 2, 2, 3])) # 输出: {1, 2, 3}
57. setattr()
为对象设置属性。
class MyClass:
pass
obj = MyClass()
setattr(obj, 'x', 10)
print(obj.x) # 输出: 10
58. slice()
返回一个切片对象。
s = slice(1, 5)
print([0, 1, 2, 3, 4, 5][s]) # 输出: [1, 2, 3, 4]
59. sorted()
返回排序后的列表。
print(sorted([3, 1, 2])) # 输出: [1, 2, 3]
60. staticmethod()
返回一个静态方法的实例。
class MyClass:
@staticmethod
def hello():
print("Hello World")
MyClass.hello() # 输出: Hello World
61. str()
将对象转换为字符串。
print(str(123)) # 输出: '123'
62. sum()
返回可迭代对象元素的总和。
print(sum([1, 2, 3])) # 输出: 6
63. super()
返回当前类的父类对象。
class A:
def hello(self):
print("Hello from A")
class B(A):
def hello(self):
super().hello()
print("Hello from B")
obj = B()
obj.hello()
# 输出:
# Hello from A
# Hello from B
64. tuple()
将可迭代对象转换为元组。
print(tuple([1, 2, 3])) # 输出: (1, 2, 3)
65. type()
返回对象的类型。
print(type(10)) # 输出: <class 'int'>
66. vars()
返回对象的__dict__属性(存储对象的属性字典)。
class MyClass:
x = 5
obj = MyClass()
print(vars(obj)) # 输出: {'x': 5}
67. zip()
将多个可迭代对象打包成元组。
print(list(zip([1, 2], ['a', 'b']))) # 输出: [(1, 'a'), (2, 'b')]
68. __import__()
动态导入模块。
math = __import__('math')
print(math.sqrt(16)) # 输出: 4.0
69. filter()
根据条件筛选出符合的元素。
def is_positive(x):
return x > 0
print(list(filter(is_positive, [-1, 2, 3]))) # 输出: [2, 3]
70. id()
返回对象的唯一标识符。
a = "hello"
print(id(a)) # 输出: 对象的唯一标识符(一个整数)
71. isinstance()
检查一个对象是否是指定类的实例。
print(isinstance(10, int)) # 输出: True
72. issubclass()
检查一个类是否是另一个类的子类。
class A: pass
class B(A): pass
print(issubclass(B, A)) # 输出: True
73. iter()
返回一个可迭代对象的迭代器。
lst = [1, 2, 3]
it = iter(lst)
print(next(it)) # 输出: 1
74. len()
返回对象的长度。
print(len("Hello")) # 输出: 5
75. list()
将可迭代对象转换为列表。
print(list((1, 2, 3))) # 输出: [1, 2, 3]
76. locals()
返回当前局部符号表的字典。
x = 10
print(locals()) # 输出: {'x': 10}
77. map()
将函数应用到可迭代对象的每一个元素。
def square(x):
return x * x
print(list(map(square, [1, 2, 3]))) # 输出: [1, 4, 9]
78. max()
返回可迭代对象中的最大值。
print(max([1, 3, 2])) # 输出: 3
79. memoryview()
返回一个内存视图对象。
b = bytearray([1, 2, 3])
m = memoryview(b)
print(m[0]) # 输出: 1
80. min()
返回可迭代对象中的最小值。
print(min([1, 3, 2])) # 输出: 1
81. next()
返回可迭代对象的下一个项目。
it = iter([1, 2, 3])
print(next(it)) # 输出: 1
82. object()
返回一个新的空对象。
obj = object()
print(obj) # 输出: <object object at 0x...>
83. oct()
将整数转换为八进制字符串。
print(oct(8)) # 输出: '0o10'
84. open()
打开一个文件,并返回文件对象。
with open('test.txt', 'w') as f:
f.write("Hello")
85. ord()
将字符转换为其对应的 Unicode 码点。
print(ord('A')) # 输出: 65
86. pow()
返回 x 的 y 次方,如果给定第三个参数,返回 x 的 y 次方对 z 取模的结果。
print(pow(2, 3)) # 输出: 8
print(pow(2, 3, 5)) # 输出: 3
87. print()
打印输出内容。
print("Hello World") # 输出: Hello World
88. property()
返回属性值的管理方法。
class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
obj = MyClass(10)
print(obj.value) # 输出: 10
89. range()
生成一个整数序列。
for i in range(5):
print(i) # 输出: 0 1 2 3 4
90. repr()
返回对象的字符串表示。
print(repr("Hello")) # 输出: "'Hello'"
91. reversed()
返回一个反转的可迭代对象。
print(list(reversed([1, 2, 3]))) # 输出: [3, 2, 1]
92. round()
返回浮点数四舍五入后的值。
print(round(3.14159, 2)) # 输出: 3.14
93. set()
创建一个集合对象。
print(set([1, 2, 2, 3])) # 输出: {1, 2, 3}
94. setattr()
为对象设置属性。
class MyClass:
pass
obj = MyClass()
setattr(obj, 'x', 10)
print(obj.x) # 输出: 10
95. slice()
返回一个切片对象。
s = slice(1, 5)
print([0, 1, 2, 3, 4, 5][s]) # 输出: [1, 2, 3, 4]
96. sorted()
返回排序后的列表。
print(sorted([3, 1, 2])) # 输出: [1, 2, 3]
97. staticmethod()
返回一个静态方法的实例。
class MyClass:
@staticmethod
def hello():
print("Hello World")
MyClass.hello() # 输出: Hello World
98. str()
将对象转换为字符串。
print(str(123)) # 输出: '123'
99. sum()
返回可迭代对象元素的总和。
print(sum([1, 2, 3])) # 输出: 6
100. zip()
将多个可迭代对象打包成元组。
print(list(zip([1, 2], ['a', 'b']))) # 输出: [(1, 'a'), (2, 'b')]
以上就是Python中一些常用函数的示例。希望有所帮助!
相关推荐
- SQL轻松入门(5):窗口函数(sql语录中加窗口函数的执行)
-
01前言标题中有2个字让我在初次接触窗口函数时,真真切切明白了何谓”高级”?说来也是一番辛酸史!话说,我见识了窗口函数的强大后,便磨拳擦掌的要试验一番,结果在查询中输入语句,返回的结果却是报错,Wh...
- 28个SQL常用的DeepSeek提示词指令,码住直接套用
-
自从DeepSeek出现后,极大地提升了大家平时的工作效率,特别是对于一些想从事数据行业的小白,只需要掌握DeepSeek的提问技巧,SQL相关的问题也不再是个门槛。...
- 从零开始学SQL进阶,数据分析师必备SQL取数技巧,建议收藏
-
上一节给大家讲到SQL取数的一些基本内容,包含SQL简单查询与高级查询,需要复习相关知识的同学可以跳转至上一节,本节给大家讲解SQL的进阶应用,在实际过程中用途比较多的子查询与窗口函数,下面一起学习。...
- SQL_OVER语法(sql语句over什么含义)
-
OVER的定义OVER用于为行定义一个窗口,它对一组值进行操作,不需要使用GROUPBY子句对数据进行分组,能够在同一行中同时返回基础行的列和聚合列。...
- SQL窗口函数知多少?(sql窗口怎么执行)
-
我们在日常工作中是否经常会遇到需要排名的情况,比如:每个部门按业绩来排名,每人按绩效排名,对部门销售业绩前N名的进行奖励等。面对这类需求,我们就需要使用sql的高级功能——窗口函数。...
- 如何学习并掌握 SQL 数据库基础:从零散查表到高效数据提取
-
无论是职场数据分析、产品运营,还是做副业项目,掌握SQL(StructuredQueryLanguage)意味着你能直接从数据库中提取、分析、整合数据,而不再依赖他人拉数,节省大量沟通成本,让你...
- SQL窗口函数(sql窗口函数执行顺序)
-
背景在数据分析中,经常会遇到按某某条件来排名、并找出排名的前几名,用日常SQL的GROUPBY,ORDERBY来实现特别的麻烦,有时甚至实现不了,这个时候SQL窗口函数就能发挥巨大作用了,窗...
- sqlserver删除重复数据只保留一条,使用ROW_NUMER()与Partition By
-
1.使用场景:公司的小程序需要实现一个功能:在原有小程序上,有一个优惠券活动表。存储着活动产品数据,但因为之前没有做约束,导致数据的不唯一,这会使打开产品详情页时,可能会出现随机显示任意活动问题。...
- SQL面试经典问题(一)(sql经典面试题及答案)
-
以下是三个精心挑选的经典SQL面试问题及其详细解决方案,涵盖了数据分析、排序限制和数据清理等常见场景。这些问题旨在考察SQL的核心技能,适用于初学者到高级开发者的面试准备。每个问题均包含清晰的...
- SQL:求连续N天的登陆人员之通用解答
-
前几天发了一个微头条:...
- SQL四大排序函数神技(sql中的排序是什么语句)
-
在日常SQL开发中,排序操作无处不在。当大家需要排序时,是否只会想到ORDERBY?今天,我们就来揭秘SQL中四个强大却常被忽略的排序函数:ROW_NUMBER()、RANK()、DENSE_RAN...
- 四、mysql窗口函数之row_number()函数的使用
-
1、窗口函数之row_number()使用背景窗口函数中,排序函数rank(),dense_rank()虽说都是排序函数,但是各有用处,假如像上章节说的“同组同分”两条数据,我们不想“班级名次”出现“...
- ROW_NUMBER()函数(rownumber函数与rank区别)
-
ROW_NUMBER()是SQL中的一个窗口函数(WindowFunction)...
- Dify「模板转换」节点终极指南:动态文本生成进阶技巧(附代码)Jinja2引擎解析
-
这篇文章是关于Dify「模板转换」节点的终极指南,解析了基于Jinja2模板引擎的动态文本生成技巧,涵盖多源文本整合、知识检索结构化、动态API构建及个性化内容生成等六大应用场景,助力开发者高效利用模...
- Python 最常用的语句、函数有哪些?
-
1.#coding=utf-8①代码中有中文字符,最好在代码前面加#coding=utf-8②pycharm不加可能不会报错,但是代码最终是会放到服务器上,放到服务器上的时候运行可能会报错。③...
- 一周热门
-
-
C# 13 和 .NET 9 全知道 :13 使用 ASP.NET Core 构建网站 (1)
-
因果推断Matching方式实现代码 因果推断模型
-
git pull命令使用实例 git pull--rebase
-
git 执行pull错误如何撤销 git pull fail
-
面试官:git pull是哪两个指令的组合?
-
git pull 和git fetch 命令分别有什么作用?二者有什么区别?
-
git fetch 和git pull 的异同 git中fetch和pull的区别
-
git pull 之后本地代码被覆盖 解决方案
-
还可以这样玩?Git基本原理及各种骚操作,涨知识了
-
git命令之pull git.pull
-
- 最近发表
- 标签列表
-
- git pull (33)
- git fetch (35)
- mysql insert (35)
- mysql distinct (37)
- concat_ws (36)
- java continue (36)
- jenkins官网 (37)
- mysql 子查询 (37)
- python元组 (33)
- mybatis 分页 (35)
- vba split (37)
- redis watch (34)
- python list sort (37)
- nvarchar2 (34)
- mysql not null (36)
- hmset (35)
- python telnet (35)
- python readlines() 方法 (36)
- munmap (35)
- docker network create (35)
- redis 集合 (37)
- python sftp (37)
- setpriority (34)
- c语言 switch (34)
- git commit (34)