python中常用的内置函数介绍

python中常用的内置函数介绍

  • [1. print()](#1. print())
  • [2. len()](#2. len())
  • [3. type()](#3. type())
  • [4. str(), int(), float()](#4. str(), int(), float())
  • [5. list(), tuple(), set(), dict()](#5. list(), tuple(), set(), dict())
  • [6. range()](#6. range())
  • [7. sum()](#7. sum())
  • [8. max(), min()](#8. max(), min())
  • [9. sorted()](#9. sorted())
  • [10. zip()](#10. zip())
  • [11. enumerate()](#11. enumerate())
  • [12. map()](#12. map())
  • [13. filter()](#13. filter())
  • [14. any(), all()](#14. any(), all())
  • [15. abs()](#15. abs())
  • [16. pow()](#16. pow())
  • [17. round()](#17. round())
  • [18. ord(), chr()](#18. ord(), chr())
  • [19. open()](#19. open())
  • [20. input()](#20. input())
  • [21. eval()](#21. eval())
  • [22. globals(), locals()](#22. globals(), locals())
  • [23. dir()](#23. dir())
  • [24. help()](#24. help())
  • [25. iter()](#25. iter())
  • [26. reversed()](#26. reversed())
  • [27. slice()](#27. slice())
  • [28. super()](#28. super())
  • [29. staticmethod(), classmethod()](#29. staticmethod(), classmethod())
  • [30. property()](#30. property())
  • [31. format()](#31. format())
  • [32. bin(), hex()](#32. bin(), hex())
  • [33. bytearray()](#33. bytearray())
  • [34. bytes()](#34. bytes())
  • [35. complex()](#35. complex())
  • [36. divmod()](#36. divmod())
  • [37. hash()](#37. hash())
  • [38. id()](#38. id())
  • [39. isinstance()](#39. isinstance())
  • [40. issubclass()](#40. issubclass())
  • [41. memoryview()](#41. memoryview())
  • [42. setattr(), getattr(), delattr()](#42. setattr(), getattr(), delattr())
  • [43. callable()](#43. callable())
  • [44. compile()](#44. compile())
  • [45. exec()](#45. exec())
  • [46. next()](#46. next())

1. print()

用于输出信息到控制台

python 复制代码
print("Hello, World!")
print("This is a test.", "More text.")

2. len()

返回容器(如列表、元组、字符串、字典等)的长度

python 复制代码
my_list = [1, 2, 3, 4]
my_string = "Hello"
my_dict = {'a': 1, 'b': 2}

print(len(my_list))  # 输出: 4
print(len(my_string))  # 输出: 5
print(len(my_dict))  # 输出: 2

3. type()

返回对象的类型

python 复制代码
print(type(123))  # 输出: <class 'int'>
print(type("Hello"))  # 输出: <class 'str'>
print(type([1, 2, 3]))  # 输出: <class 'list'>

4. str(), int(), float()

将其他类型转换为字符串、整数、浮点数

python 复制代码
print(str(123))  # 输出: '123'
print(int("123"))  # 输出: 123
print(float("123.45"))  # 输出: 123.45

5. list(), tuple(), set(), dict()

将其他类型转换为列表、元组、集合、字典

python 复制代码
print(list("Hello"))  # 输出: ['H', 'e', 'l', 'l', 'o']
print(tuple([1, 2, 3]))  # 输出: (1, 2, 3)
print(set([1, 2, 2, 3, 3]))  # 输出: {1, 2, 3}
print(dict([('a', 1), ('b', 2)]))  # 输出: {'a': 1, 'b': 2}

6. range()

生成一个整数序列

python 复制代码
print(list(range(5)))  # 输出: [0, 1, 2, 3, 4]
print(list(range(1, 6)))  # 输出: [1, 2, 3, 4, 5]
print(list(range(1, 10, 2)))  # 输出: [1, 3, 5, 7, 9]

7. sum()

返回一个可迭代对象中所有元素的和

python 复制代码
print(sum([1, 2, 3, 4]))  # 输出: 10
print(sum([1.5, 2.5, 3.5]))  # 输出: 7.5

8. max(), min()

返回可迭代对象中的最大值和最小值

python 复制代码
print(max([1, 2, 3, 4]))  # 输出: 4
print(min([1, 2, 3, 4]))  # 输出: 1
print(max("abc"))  # 输出: 'c'
print(min("abc"))  # 输出: 'a'

9. sorted()

返回一个排序后的列表

python 复制代码
print(sorted([3, 1, 4, 1, 5, 9]))  # 输出: [1, 1, 3, 4, 5, 9]
print(sorted("python"))  # 输出: ['h', 'n', 'o', 'p', 't', 'y']
print(sorted([3, 1, 4, 1, 5, 9], reverse=True))  # 输出: [9, 5, 4, 3, 1, 1]

10. zip()

将多个可迭代对象中的元素配对,返回一个元组的迭代器

python 复制代码
names = ["ZhangSan", "LiSi", "Wangwu"]
scores = [90, 85, 92]

for name, score in zip(names, scores):
    print(name, score)

# 输出:
# ZhangSan 90
# LiSi 85
# Wangwu 92

11. enumerate()

在迭代中提供元素的索引

python 复制代码
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(index, fruit)

# 输出:
# 0 apple
# 1 banana
# 2 cherry

12. map()

对可迭代对象中的每个元素应用一个函数,返回一个迭代器

python 复制代码
def square(x):
    return x * x

numbers = [1, 2, 3, 4]
squared = map(square, numbers)

print(list(squared))  # 输出: [1, 4, 9, 16]

13. filter()

过滤可迭代对象中的元素,返回一个迭代器

python 复制代码
def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
evens = filter(is_even, numbers)

print(list(evens))  # 输出: [2, 4, 6]

14. any(), all()

检查可迭代对象中的元素是否满足条件

python 复制代码
print(any([True, False, False]))  # 输出: True
print(all([True, False, False]))  # 输出: False
print(all([True, True, True]))  # 输出: True

15. abs()

返回一个数的绝对值

python 复制代码
print(abs(-10))  # 输出: 10
print(abs(10))  # 输出: 10
print(abs(-3.5))  # 输出: 3.5

16. pow()

计算 x 的 y 次幂

python 复制代码
print(pow(2, 3))  # 输出: 8
print(pow(2, 3, 5))  # 输出: 3 (2^3 % 5 = 8 % 5 = 3)

17. round()

返回一个数的四舍五入值

python 复制代码
print(round(3.14159, 2))  # 输出: 3.14
print(round(3.14159))  # 输出: 3
print(round(3.14159, 3))  # 输出: 3.142

18. ord(), chr()

ord() 返回字符的 Unicode 码点,chr() 返回给定 Unicode 码点的字符

python 复制代码
print(ord('A'))  # 输出: 65
print(chr(65))  # 输出: 'A'

19. open()

打开文件并返回一个文件对象

python 复制代码
with open('example.txt', 'w') as file:
    file.write('Hello, World!')

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)  # 输出: Hello, World!

20. input()

从标准输入读取一行文本

python 复制代码
name = input("What is your name? ")
print(f"Hello, {name}!")

21. eval()

执行一个字符串表达式并返回结果

python 复制代码
result = eval("2 + 3 * 4")
print(result)  # 输出: 14

22. globals(), locals()

返回全局和局部命名空间的字典

python 复制代码
x = 10
globals_dict = globals()
locals_dict = locals()

print(globals_dict['x'])  # 输出: 10
print(locals_dict['x'])  # 输出: 10

23. dir()

返回模块、类、对象的属性和方法列表

python 复制代码
print(dir(str))  # 输出: ['__add__', '__class__', ...]
print(dir())  # 输出: 当前命名空间中的所有变量

24. help()

获取对象的帮助信息

python 复制代码
help(list)

25. iter()

返回一个对象的迭代器

python 复制代码
my_list = [1, 2, 3]
it = iter(my_list)

print(next(it))  # 输出: 1
print(next(it))  # 输出: 2
print(next(it))  # 输出: 3

26. reversed()

返回一个逆序的迭代器

python 复制代码
my_list = [1, 2, 3, 4]
rev = reversed(my_list)

print(list(rev))  # 输出: [4, 3, 2, 1]

27. slice()

创建一个切片对象,用于切片操作

python 复制代码
s = slice(1, 5, 2)
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[s])  # 输出: [1, 3]

28. super()

在子类中调用父类的方法

python 复制代码
class Parent:
    def say_hello(self):
        print("Hello from Parent")

class Child(Parent):
    def say_hello(self):
        super().say_hello()
        print("Hello from Child")

child = Child()
child.say_hello()

# 输出:
# Hello from Parent
# Hello from Child

29. staticmethod(), classmethod()

定义静态方法和类方法

python 复制代码
class MyClass:
    @staticmethod
    def static_method():
        print("This is a static method")

    @classmethod
    def class_method(cls):
        print(f"This is a class method of {cls}")

MyClass.static_method()  # 输出: This is a static method
MyClass.class_method()  # 输出: This is a class method of <class '__main__.MyClass'>

30. property()

定义属性

python 复制代码
class Person:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        self._name = value

person = Person("ZhangSan")
print(person.name)  # 输出: ZhangSan
person.name = "LiSi"
print(person.name)  # 输出: LiSi

31. format()

用于格式化字符串

python 复制代码
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
print(f"My name is {name} and I am {age} years old.")  # 使用 f-string

32. bin(), hex()

返回一个整数的二进制和十六进制表示

python 复制代码
print(bin(10))  # 输出: '0b1010'
print(hex(10))  # 输出: '0xa'

33. bytearray()

返回一个可变的字节数组

python 复制代码
b = bytearray([65, 66, 67])
print(b)  # 输出: bytearray(b'ABC')
b[0] = 64
print(b)  # 输出: bytearray(b'@BC')

34. bytes()

返回一个不可变的字节数组

python 复制代码
b = bytes([65, 66, 67])
print(b)  # 输出: b'ABC'
# b[0] = 64  # 这行会引发 TypeError

35. complex()

返回一个复数

python 复制代码
z = complex(3, 4)
print(z)  # 输出: (3+4j)
print(z.real)  # 输出: 3.0
print(z.imag)  # 输出: 4.0

36. divmod()

返回商和余数的元组

python 复制代码
print(divmod(10, 3))  # 输出: (3, 1)

37. hash()

返回对象的哈希值

python 复制代码
print(hash("Hello"))  # 输出: 4190775692919092328
print(hash(3.14))  # 输出: 4612220020592406118

38. id()

返回对象的唯一标识符

python 复制代码
x = 10
print(id(x))  # 输出: 140723320781200

39. isinstance()

检查对象是否是指定类型

python 复制代码
print(isinstance(10, int))  # 输出: True
print(isinstance("Hello", str))  # 输出: True
print(isinstance([1, 2, 3], list))  # 输出: True

40. issubclass()

检查一个类是否是另一个类的子类

python 复制代码
class Animal:
    pass

class Dog(Animal):
    pass

print(issubclass(Dog, Animal))  # 输出: True
print(issubclass(Animal, Dog))  # 输出: False

41. memoryview()

返回一个内存视图对象

python 复制代码
b = bytearray(b'Hello')
m = memoryview(b)
print(m[0])  # 输出: 72
m[0] = 87  # 修改内存视图中的值
print(b)  # 输出: bytearray(b'World')

42. setattr(), getattr(), delattr()

设置、获取和删除对象的属性

python 复制代码
class Person:
    def __init__(self, name):
        self.name = name

p = Person("Alice")
setattr(p, "age", 30)
print(getattr(p, "age"))  # 输出: 30
delattr(p, "age")
print(hasattr(p, "age"))  # 输出: False

43. callable()

检查对象是否是可调用的(即是否可以作为函数调用)

python 复制代码
def my_function():
    pass

print(callable(my_function))  # 输出: True
print(callable(123))  # 输出: False

44. compile()

编译 Python 源代码

python 复制代码
code = "x = 5\nprint(x)"
compiled_code = compile(code, "<string>", "exec")
exec(compiled_code)  # 输出: 5

45. exec()

执行动态生成的 Python 代码

python 复制代码
code = "x = 5\nprint(x)"
exec(code)  # 输出: 5

46. next()

获取迭代器的下一个元素

python 复制代码
my_list = [1, 2, 3]
it = iter(my_list)

print(next(it))  # 输出: 1
print(next(it))  # 输出: 2
print(next(it))  # 输出: 3
相关推荐
一个小白1几秒前
C++——list模拟实现
开发语言·c++
bug总结几秒前
新学一个JavaScript 的 classList API
开发语言·javascript·ecmascript
Nicole Potter7 分钟前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
liuyuzhongcc9 分钟前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
鸟哥大大18 分钟前
【Python】pypinyin-汉字拼音转换工具
python·自然语言处理
sjsjsbbsbsn22 分钟前
Spring Boot定时任务原理
java·spring boot·后端
jiugie26 分钟前
MongoDB学习
数据库·python·mongodb
靡不有初11134 分钟前
CCF-CSP第18次认证第一题——报数【两个与string相关的函数的使用】
c++·学习·ccfcsp
xmweisi43 分钟前
【华为】报文统计的技术NetStream
运维·服务器·网络·华为认证
十八朵郁金香1 小时前
通俗易懂的DOM1级标准介绍
开发语言·前端·javascript