欢迎访问宙启技术站
智能推送

常用的Python内置函数大全,不容错过

发布时间:2024-01-11 17:05:55

Python是一种高级编程语言,它包含了许多内置函数,这些函数在日常编程中非常常用且非常方便。下面是一些常用的Python内置函数的大全及其使用示例:

1. print():打印输出。

print("Hello, World!")

2. input():从用户输入获取数据。

name = input("What is your name?")
print("Hello, " + name)

3. len():获取字符串、列表、元组等的长度。

s = "Hello, World!"
print(len(s)) # 输出 13

4. type():获取变量或值的类型。

x = 10
print(type(x)) # 输出 <class 'int'>

5. str():将其他类型转换为字符串。

x = 10
print("The value of x is " + str(x))

6. int():将字符串或其他类型转换为整数。

x = int("10")
print(x * 2) # 输出 20

7. float():将字符串或其他类型转换为浮点数。

x = float("3.14")
print(x + 1) # 输出 4.14

8. list():将字符串、元组或其他可迭代对象转换为列表。

s = "Hello"
print(list(s)) # 输出 ['H', 'e', 'l', 'l', 'o']

9. tuple():将字符串、列表或其他可迭代对象转换为元组。

l = [1, 2, 3]
print(tuple(l)) # 输出 (1, 2, 3)

10. range():生成一个指定范围的数字序列。

for i in range(5):
    print(i) # 输出 0, 1, 2, 3, 4

11. max():获取列表、元组或字符串中的最大值。

l = [1, 2, 3]
print(max(l)) # 输出 3

12. min():获取列表、元组或字符串中的最小值。

l = [1, 2, 3]
print(min(l)) # 输出 1

13. sum():计算列表或元组中所有元素的和。

l = [1, 2, 3]
print(sum(l)) # 输出 6

14. abs():获取一个数的绝对值。

x = -10
print(abs(x)) # 输出 10

15. round():对一个浮点数进行四舍五入。

x = 3.1415
print(round(x, 2)) # 输出 3.14

16. sorted():对列表、元组等可迭代对象进行排序。

l = [3, 1, 2]
print(sorted(l)) # 输出 [1, 2, 3]

17. enumerate():枚举列表、元组等可迭代对象的索引及其对应的值。

l = ["a", "b", "c"]
for index, value in enumerate(l):
    print(index, value)
# 输出:
# 0 a
# 1 b
# 2 c

18. zip():将多个可迭代对象的元素打包成元组。

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(name, age)
# 输出:
# Alice 25
# Bob 30
# Charlie 35

19. map():对可迭代对象的每个元素应用指定的函数。

l = [1, 2, 3]
squared = map(lambda x: x ** 2, l)
print(list(squared)) # 输出 [1, 4, 9]

20. filter():筛选出可迭代对象中符合条件的元素。

l = [1, 2, 3, 4, 5]
even = filter(lambda x: x % 2 == 0, l)
print(list(even)) # 输出 [2, 4]

这只是Python内置函数的一小部分。通过了解和熟练使用这些函数,可以使编写Python代码变得更加高效和简洁。希望这个简短的列表对您有所帮助!