来源:网络
基础函数是构建复杂程序的基石。熟练掌握这些函数,能让你的编程效率大幅提升。今天就为大家详细介绍 50 个 Python 基础函数,看看你都知道哪些!num = int(3.14)print(num) # 输出: 3
num = float(3)print(num) # 输出: 3.0
3.str():将对象转换为字符串。
num = 123string = str(num)print(string, type(string)) # 输出: 123 <class'str'>
4.bool():把数据转换为布尔值,0、空字符串、空列表等转换为False,其他为True。
print(bool(0)) # 输出: Falseprint(bool([1])) # 输出: True
5.list():将可迭代对象转换为列表。
tuple_data = (1, 2, 3)lst = list(tuple_data)print(lst) # 输出: [1, 2, 3]
6.tuple():把可迭代对象转换为元组。
lst = [4, 5, 6]tup = tuple(lst)print(tup) # 输出: (4, 5, 6)
7.set():将可迭代对象转换为集合,自动去重。
lst = [1, 2, 2, 3]s = set(lst)print(s) # 输出: {1, 2, 3}
8.dict():创建字典,可通过多种方式初始化。
d = dict(a=1, b=2)print(d) # 输出: {'a': 1, 'b': 2}
9.abs():返回数字的绝对值。
10round():对数字进行四舍五入。
print(round(3.14159, 2)) # 输出: 3.14
11.sum():计算可迭代对象中元素的总和。
lst = [1, 2, 3]print(sum(lst)) # 输出: 6
12.min():返回可迭代对象中的最小值。
print(min([5, 3, 7])) # 输出: 3
13.max():返回可迭代对象中的最大值。
print(max([10, 15, 8])) # 输出: 15
14.pow():计算一个数的幂次方。
15.len():获取序列(列表、字符串、元组等)的长度。
string = "hello"print(len(string)) # 输出: 5
16.sorted():对可迭代对象进行排序,返回新的排序后的列表。
lst = [3, 1, 2]print(sorted(lst)) # 输出: [1, 2, 3]
17.reversed():反转序列,返回一个迭代器。
lst = [1, 2, 3]for num in reversed(lst):print(num) # 依次输出: 3 2 1
18.enumerate():将可迭代对象组合为一个索引序列,常用于遍历。
fruits = ["apple", "banana", "cherry"]forindex, fruit in enumerate(fruits):print(index, fruit)
19.zip():将多个可迭代对象对应位置的元素组合成元组,返回一个迭代器。
list1 = [1, 2, 3]list2 = ['a', 'b', 'c']for pair in zip(list1, list2):print(pair) # 依次输出: (1, 'a') (2, 'b') (3, 'c')
20.print():输出函数,可打印多个对象,用逗号分隔。
print("Hello", "World") # 输出: Hello World
21.input():获取用户输入,返回字符串类型。
user_input = input("请输入内容: ")print(user_input)
22.open():打开文件,返回文件对象。
file = open('test.txt', 'w') # 以写入模式打开文件file.close() # 关闭文件
23.file.read():读取文件内容。
file = open('test.txt', 'r')content = file.read()print(content)file.close()
24.file.write():向文件中写入内容。
file = open('test.txt', 'w')file.write("Hello, file!")file.close()
25.str.capitalize():将字符串的首字母大写。
string = "python is fun"print(string.capitalize()) # 输出: Python isfun
26.str.upper():将字符串转换为大写。
print("hello".upper()) # 输出: HELLO
27.str.lower():将字符串转换为小写。
print("WORLD".lower()) # 输出: world
28.str.strip():去除字符串两端的空白字符。
string = " python "print(string.strip()) # 输出: python
29.str.split():根据指定分隔符分割字符串,返回列表。
string = "apple,banana,cherry"print(string.split(',')) # 输出: ['apple', 'banana', 'cherry']
30.str.join():用指定字符串连接列表中的元素。
lst = ['a', 'b', 'c']print(''.join(lst)) # 输出: abc
31.def:用于定义函数,是创建自定义函数的关键。
defadd(a, b):return a + b
32.lambda:创建匿名函数,简洁地定义小型函数。
add = lambda x, y: x + yprint(add(3, 4)) # 输出: 7
33.help():查看函数或模块的帮助文档。
34.range():生成指定范围的整数序列,常用于循环。
for i in range(5):print(i) # 依次输出: 0 1 2 3 4
35.isinstance():判断对象是否为指定类型。
print(isinstance(5, int)) # 输出: True
36.filter():过滤可迭代对象,根据函数返回的布尔值筛选元素。
lst = [1, 2, 3, 4, 5]result = list(filter(lambda x: x % 2 == 0, lst))print(result) # 输出: [2, 4]
37.map():对可迭代对象中的每个元素应用函数,返回新的迭代器。
lst = [1, 2, 3]result = list(map(lambda x: x * 2, lst))print(result) # 输出: [2, 4, 6]
38.all():判断可迭代对象中的所有元素是否都为True。
print(all([True, True, False])) # 输出: False
39.any():判断可迭代对象中是否有元素为True。
print(any([False, False, True])) # 输出: True
40.id():返回对象的唯一标识符。
41.type():返回对象的类型。
print(type("hello")) # 输出: <class'str'>
42.dir():列出对象的属性和方法。
43.globals():返回全局作用域中的所有变量和函数。
44.locals():返回局部作用域中的所有变量和函数。
def func():x = 10print(locals())func()
45.eval():计算字符串形式的 Python 表达式。
result = eval("1 + 2 * 3")print(result) # 输出: 7
46.exec():执行字符串形式的 Python 代码。
exec("print('Hello, exec!')")
47.format():格式化字符串。
name = "Alice"age = 25print("我的名字是{},今年{}岁。".format(name, age))
48.hash():返回对象的哈希值。
49.memoryview():返回对象的内存视图。
byte_data = bytes([1, 2, 3])mv = memoryview(byte_data)print(mv)
50.next():获取迭代器的下一个元素。
it = iter([1, 2, 3])print(next(it)) # 输出: 1
以上这50个Python基础函数,在编程中使用频率极高。熟练掌握它们,能让你在Python编程的道路上更加得心应手。你都熟练掌握了吗?如果还有不熟悉的函数,赶紧动手实践起来吧!介绍了50个Python基础函数。若你觉得某些函数的讲解需要更深入,或想增减函数,欢迎随时告诉我。