当前位置: 首页 > news >正文

python中常用的内置函数介绍

python中常用的内置函数介绍

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

1. print()

用于输出信息到控制台

print("Hello, World!")
print("This is a test.", "More text.")

2. len()

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

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

返回对象的类型

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

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

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

print(str(123))  # 输出: '123'
print(int("123"))  # 输出: 123
print(float("123.45"))  # 输出: 123.45

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

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

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

生成一个整数序列

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

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

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

8. max(), min()

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

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

9. sorted()

返回一个排序后的列表

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

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

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

在迭代中提供元素的索引

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):print(index, fruit)# 输出:
# 0 apple
# 1 banana
# 2 cherry

12. map()

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

def square(x):return x * xnumbers = [1, 2, 3, 4]
squared = map(square, numbers)print(list(squared))  # 输出: [1, 4, 9, 16]

13. filter()

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

def is_even(x):return x % 2 == 0numbers = [1, 2, 3, 4, 5, 6]
evens = filter(is_even, numbers)print(list(evens))  # 输出: [2, 4, 6]

14. any(), all()

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

print(any([True, False, False]))  # 输出: True
print(all([True, False, False]))  # 输出: False
print(all([True, True, True]))  # 输出: True

15. abs()

返回一个数的绝对值

print(abs(-10))  # 输出: 10
print(abs(10))  # 输出: 10
print(abs(-3.5))  # 输出: 3.5

16. pow()

计算 x 的 y 次幂

print(pow(2, 3))  # 输出: 8
print(pow(2, 3, 5))  # 输出: 3 (2^3 % 5 = 8 % 5 = 3)

17. round()

返回一个数的四舍五入值

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 码点的字符

print(ord('A'))  # 输出: 65
print(chr(65))  # 输出: 'A'

19. open()

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

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

从标准输入读取一行文本

name = input("What is your name? ")
print(f"Hello, {name}!")

21. eval()

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

result = eval("2 + 3 * 4")
print(result)  # 输出: 14

22. globals(), locals()

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

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

23. dir()

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

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

24. help()

获取对象的帮助信息

help(list)

25. iter()

返回一个对象的迭代器

my_list = [1, 2, 3]
it = iter(my_list)print(next(it))  # 输出: 1
print(next(it))  # 输出: 2
print(next(it))  # 输出: 3

26. reversed()

返回一个逆序的迭代器

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

27. slice()

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

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

在子类中调用父类的方法

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

定义静态方法和类方法

class MyClass:@staticmethoddef static_method():print("This is a static method")@classmethoddef 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()

定义属性

class Person:def __init__(self, name):self._name = name@propertydef name(self):return self._name@name.setterdef name(self, value):self._name = valueperson = Person("ZhangSan")
print(person.name)  # 输出: ZhangSan
person.name = "LiSi"
print(person.name)  # 输出: LiSi

31. format()

用于格式化字符串

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

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

print(bin(10))  # 输出: '0b1010'
print(hex(10))  # 输出: '0xa'

33. bytearray()

返回一个可变的字节数组

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

34. bytes()

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

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

35. complex()

返回一个复数

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

36. divmod()

返回商和余数的元组

print(divmod(10, 3))  # 输出: (3, 1)

37. hash()

返回对象的哈希值

print(hash("Hello"))  # 输出: 4190775692919092328
print(hash(3.14))  # 输出: 4612220020592406118

38. id()

返回对象的唯一标识符

x = 10
print(id(x))  # 输出: 140723320781200

39. isinstance()

检查对象是否是指定类型

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

40. issubclass()

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

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

41. memoryview()

返回一个内存视图对象

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

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

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

class Person:def __init__(self, name):self.name = namep = Person("Alice")
setattr(p, "age", 30)
print(getattr(p, "age"))  # 输出: 30
delattr(p, "age")
print(hasattr(p, "age"))  # 输出: False

43. callable()

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

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

44. compile()

编译 Python 源代码

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

45. exec()

执行动态生成的 Python 代码

code = "x = 5\nprint(x)"
exec(code)  # 输出: 5

46. next()

获取迭代器的下一个元素

my_list = [1, 2, 3]
it = iter(my_list)print(next(it))  # 输出: 1
print(next(it))  # 输出: 2
print(next(it))  # 输出: 3

相关文章:

python中常用的内置函数介绍

python中常用的内置函数介绍 1. print()2. len()3. type()4. str(), int(), float()5. list(), tuple(), set(), dict()6. range()7. sum()8. max(), min()9. sorted()10. zip()11. enumerate()12. map()13. filter()14. any(), all()15. abs()16. pow()17. round()18. ord(), …...

【微服务】Spring Cloud Config解决的问题和案例

文章目录 强烈推荐引言解决问题1. 配置管理的集中化2. 配置的版本控制3. 环境特定配置4. 配置的动态刷新5. 安全管理敏感数据6. 配置的一致性 组件1. **配置服务器&#xff08;Config Server&#xff09;**2. **配置客户端&#xff08;Config Client&#xff09;** 配置示例配置…...

华为OD机试E卷 --最小的调整次数--24年OD统一考试(Java JS Python C C++)

文章目录 题目描述输入描述输出描述用例题目解析JS算法源码Java算法源码python算法源码c算法源码c++算法源码题目描述 有一个特异性的双端队列一,该队列可以从头部或尾部添加数据,但是只能从头部移出数据。 小A依次执行2n个指令往队列中添加数据和移出数据。其中n个指令是添…...

Oracle Dataguard(主库为 Oracle 11g 单节点)配置详解(2):配置主数据库

Oracle Dataguard&#xff08;主库为 Oracle 11g 单节点&#xff09;配置详解&#xff08;2&#xff09;&#xff1a;配置主数据库 目录 Oracle Dataguard&#xff08;主库为 Oracle 11g 单节点&#xff09;配置详解&#xff08;2&#xff09;&#xff1a;配置主数据库一、配置…...

慧集通iPaaS集成平台低代码训练-实践篇

练习使用帐号信息&#xff1a; 1.致远A8平台&#xff08;请自行准备测试环境&#xff09; 慧集通连接器配置相关信息 访问地址&#xff1a; rest账号&#xff1a;rest rest密码&#xff1a; OA账号&#xff1a; 2.云星空&#xff08;请自行准备测试环境&#xff09; 连接…...

TDengine 如何进行高效数据建模

1.背景 数据建模对于数据库建立后整体高效运行非常关键&#xff0c;不同建模方式&#xff0c;可能会产生相差几倍的性能差别 2. 建库 建模在建库阶段应考虑几下几点&#xff1a; 建多少库 根据业务情况确定建库个数&#xff0c;TDengine 不支持跨库查询&#xff0c;如果业…...

HarmonyOS NEXT应用开发实战:一分钟写一个网络接口,JsonFormat插件推荐

在开发鸿蒙操作系统应用时&#xff0c;网络接口的实现往往是一个繁琐且重复的过程。为了提高开发效率&#xff0c;坚果派(nutpi.net)特别推出了一个非常实用的插件——JsonFormat。这款插件的主要功能是将JSON格式的数据直接转换为arkts的结构定义&#xff0c;让我们在编写接口…...

基于动力学的MPC控制器设计盲点解析

文章目录 Apollo MPC控制器的设计架构误差模型和离散化预测模型推导目标函数和约束设计优化求解优化OSQP求解器参考文献 Apollo MPC控制器的设计架构 误差模型和离散化 状态变量和控制变量 1、Apollo MPC控制器中状态变量主要有如下6个 matrix_state_ Matrix::Zero(basic_stat…...

Java重要面试名词整理(十六):SpringBoot

由于SpringBoot和Spring、SpringMVC重合度较高&#xff0c;更多详细内容请参考https://blog.csdn.net/weixin_73195042/article/details/144632385 本文着重于SpringBoot的启动流程 文章目录 概念启动流程底层分析构造SpringApplication对象run(String... args)方法SpringBoo…...

在K8S中,如何部署kubesphere?

在Kubernetes集群中&#xff0c;对于一些基础能力较弱的群体来说K8S控制面板操作存在一定的难度&#xff0c;此时kubesphere可以有效的解决这类难题。以下是部署kubesphere的操作步骤&#xff1a; 操作部署&#xff1a; 1. 部署nfs共享存储目录 yum -y install nfs-server e…...

算法-查找缺失的数字

给定一个包含 [0, n] 中 n 个数的数组 nums &#xff0c;找出 [0, n] 这个范围内没有出现在数组中的那个数。 示例 1&#xff1a; 输入&#xff1a;nums [3,0,1] 输出&#xff1a;2 解释&#xff1a;n 3&#xff0c;因为有 3 个数字&#xff0c;所以所有的数字都在范围 [0,3…...

antd-vue - - - - - a-date-picker限制选择范围

antd-vue - - - - - a-date-picker限制选择范围 1. 效果展示2. 代码展示 1. 效果展示 如图&#xff1a;限制选择范围为 今年 & 去年 的 月份. 2. 代码展示 <template><a-date-picker:disabledDate"disabledDate"picker"month"/> &l…...

计算机网络练习题

学习这么多啦&#xff0c;那就简单写几个选择题巩固一下吧&#xff01; 1. 在IPv4分组各字段中&#xff0c;以下最适合携带隐藏信息的是&#xff08;D&#xff09; A、源IP地址 B、版本 C、TTL D、标识 2. OSI 参考模型中&#xff0c;数据链路层的主要功能是&#xff08;…...

redis的集群模式与ELK基础

一、redis的集群模式 1.主从复制 &#xff08;1&#xff09;概述 主从模式&#xff1a;这是redis高可用的基础&#xff0c;哨兵和集群都是建立在此基础之上。 主从模式和数据库的主从模式是一样的&#xff0c;主负责写入&#xff0c;然后把写入的数据同步到从服务器&#xff…...

STM32-笔记18-呼吸灯

1、实验目的 使用定时器 4 通道 3 生成 PWM 波控制 LED1 &#xff0c;实现呼吸灯效果。 频率&#xff1a;2kHz&#xff0c;PSC71&#xff0c;ARR499 利用定时器溢出公式 周期等于频率的倒数。故Tout 1/2KHZ&#xff1b;Ft 72MHZ PSC71&#xff08;喜欢设置成Ft的倍数&…...

Vue3 + ElementPlus动态合并数据相同的单元格(超级详细版)

最近的新项目有个需求需要合并单元列表。ElementPlus 的 Table 提供了合并行或列的方法&#xff0c;可以参考一下https://element-plus.org/zh-CN/component/table.html 但项目中&#xff0c;后台数据返回格式和指定合并是动态且没有规律的&#xff0c;Element 的示例过于简单&…...

【JavaWeb后端学习笔记】MySQL的数据控制语言(Data Control Language,DCL)

MySQL DCL 1、管理用户2、控制权限 DCL英文全称是Data Control Language&#xff08;数据控制语言&#xff09;&#xff0c;用来管理数据库用户、控制数据库访问权限。 1、管理用户 管理用户的操作都需要在MySQL自带的 mysql 数据库中进行。 -- 查询用户 -- 需要先切换到MyS…...

libvirt学习

文章目录 libvirt 简介节点、Hypervisor和域libvirt 安装和配置libvirt的XML配置文件libvirt APIMain libvirt APIsError handlingSpecial specific APIs 建立到Hypervisor的连接libvirt API使用编译libvirt工具virshvirt-clonevirt-dfvirt-imagevirt-installvirt-topvirt-what…...

STM32-笔记19-串口打印功能

复制项目文件夹03-流水灯&#xff0c;重命名为19-串口打印功能 打开项目 在主函数中&#xff0c;添加头文件、和串口初始化函数&#xff08;设置波特率&#xff09;和输出函数&#xff0c;如图所示&#xff1a; 软件部分就设置好了 下面是硬件部分 接线&#xff1a;使用USB…...

概率论与数理统计

概率论占比更多&#xff0c;三分之二左右 数理统计会少一些 事件之间的概率 ab互斥&#xff0c;不是ab独立 古典概型吃高中基础&#xff0c;考的不会很多 条件概率公式&#xff0c;要记 公式不要全记&#xff0c;很多有名称的公式是通过基础公式转换而来的 目的在于解决一…...

Python爬虫实战:研究MechanicalSoup库相关技术

一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...

Linux相关概念和易错知识点(42)(TCP的连接管理、可靠性、面临复杂网络的处理)

目录 1.TCP的连接管理机制&#xff08;1&#xff09;三次握手①握手过程②对握手过程的理解 &#xff08;2&#xff09;四次挥手&#xff08;3&#xff09;握手和挥手的触发&#xff08;4&#xff09;状态切换①挥手过程中状态的切换②握手过程中状态的切换 2.TCP的可靠性&…...

对WWDC 2025 Keynote 内容的预测

借助我们以往对苹果公司发展路径的深入研究经验&#xff0c;以及大语言模型的分析能力&#xff0c;我们系统梳理了多年来苹果 WWDC 主题演讲的规律。在 WWDC 2025 即将揭幕之际&#xff0c;我们让 ChatGPT 对今年的 Keynote 内容进行了一个初步预测&#xff0c;聊作存档。等到明…...

如何在看板中有效管理突发紧急任务

在看板中有效管理突发紧急任务需要&#xff1a;设立专门的紧急任务通道、重新调整任务优先级、保持适度的WIP&#xff08;Work-in-Progress&#xff09;弹性、优化任务处理流程、提高团队应对突发情况的敏捷性。其中&#xff0c;设立专门的紧急任务通道尤为重要&#xff0c;这能…...

【2025年】解决Burpsuite抓不到https包的问题

环境&#xff1a;windows11 burpsuite:2025.5 在抓取https网站时&#xff0c;burpsuite抓取不到https数据包&#xff0c;只显示&#xff1a; 解决该问题只需如下三个步骤&#xff1a; 1、浏览器中访问 http://burp 2、下载 CA certificate 证书 3、在设置--隐私与安全--…...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...

Xen Server服务器释放磁盘空间

disk.sh #!/bin/bashcd /run/sr-mount/e54f0646-ae11-0457-b64f-eba4673b824c # 全部虚拟机物理磁盘文件存储 a$(ls -l | awk {print $NF} | cut -d. -f1) # 使用中的虚拟机物理磁盘文件 b$(xe vm-disk-list --multiple | grep uuid | awk {print $NF})printf "%s\n"…...

技术栈RabbitMq的介绍和使用

目录 1. 什么是消息队列&#xff1f;2. 消息队列的优点3. RabbitMQ 消息队列概述4. RabbitMQ 安装5. Exchange 四种类型5.1 direct 精准匹配5.2 fanout 广播5.3 topic 正则匹配 6. RabbitMQ 队列模式6.1 简单队列模式6.2 工作队列模式6.3 发布/订阅模式6.4 路由模式6.5 主题模式…...

MySQL 知识小结(一)

一、my.cnf配置详解 我们知道安装MySQL有两种方式来安装咱们的MySQL数据库&#xff0c;分别是二进制安装编译数据库或者使用三方yum来进行安装,第三方yum的安装相对于二进制压缩包的安装更快捷&#xff0c;但是文件存放起来数据比较冗余&#xff0c;用二进制能够更好管理咱们M…...

mac 安装homebrew (nvm 及git)

mac 安装nvm 及git 万恶之源 mac 安装这些东西离不开Xcode。及homebrew 一、先说安装git步骤 通用&#xff1a; 方法一&#xff1a;使用 Homebrew 安装 Git&#xff08;推荐&#xff09; 步骤如下&#xff1a;打开终端&#xff08;Terminal.app&#xff09; 1.安装 Homebrew…...