当前位置: 首页 > 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;很多有名称的公式是通过基础公式转换而来的 目的在于解决一…...

【根据当天日期输出明天的日期(需对闰年做判定)。】2022-5-15

缘由根据当天日期输出明天的日期(需对闰年做判定)。日期类型结构体如下&#xff1a; struct data{ int year; int month; int day;};-编程语言-CSDN问答 struct mdata{ int year; int month; int day; }mdata; int 天数(int year, int month) {switch (month){case 1: case 3:…...

【HarmonyOS 5.0】DevEco Testing:鸿蒙应用质量保障的终极武器

——全方位测试解决方案与代码实战 一、工具定位与核心能力 DevEco Testing是HarmonyOS官方推出的​​一体化测试平台​​&#xff0c;覆盖应用全生命周期测试需求&#xff0c;主要提供五大核心能力&#xff1a; ​​测试类型​​​​检测目标​​​​关键指标​​功能体验基…...

《从零掌握MIPI CSI-2: 协议精解与FPGA摄像头开发实战》-- CSI-2 协议详细解析 (一)

CSI-2 协议详细解析 (一&#xff09; 1. CSI-2层定义&#xff08;CSI-2 Layer Definitions&#xff09; 分层结构 &#xff1a;CSI-2协议分为6层&#xff1a; 物理层&#xff08;PHY Layer&#xff09; &#xff1a; 定义电气特性、时钟机制和传输介质&#xff08;导线&#…...

大数据零基础学习day1之环境准备和大数据初步理解

学习大数据会使用到多台Linux服务器。 一、环境准备 1、VMware 基于VMware构建Linux虚拟机 是大数据从业者或者IT从业者的必备技能之一也是成本低廉的方案 所以VMware虚拟机方案是必须要学习的。 &#xff08;1&#xff09;设置网关 打开VMware虚拟机&#xff0c;点击编辑…...

html-<abbr> 缩写或首字母缩略词

定义与作用 <abbr> 标签用于表示缩写或首字母缩略词&#xff0c;它可以帮助用户更好地理解缩写的含义&#xff0c;尤其是对于那些不熟悉该缩写的用户。 title 属性的内容提供了缩写的详细说明。当用户将鼠标悬停在缩写上时&#xff0c;会显示一个提示框。 示例&#x…...

使用Spring AI和MCP协议构建图片搜索服务

目录 使用Spring AI和MCP协议构建图片搜索服务 引言 技术栈概览 项目架构设计 架构图 服务端开发 1. 创建Spring Boot项目 2. 实现图片搜索工具 3. 配置传输模式 Stdio模式&#xff08;本地调用&#xff09; SSE模式&#xff08;远程调用&#xff09; 4. 注册工具提…...

JavaScript基础-API 和 Web API

在学习JavaScript的过程中&#xff0c;理解API&#xff08;应用程序接口&#xff09;和Web API的概念及其应用是非常重要的。这些工具极大地扩展了JavaScript的功能&#xff0c;使得开发者能够创建出功能丰富、交互性强的Web应用程序。本文将深入探讨JavaScript中的API与Web AP…...

无人机侦测与反制技术的进展与应用

国家电网无人机侦测与反制技术的进展与应用 引言 随着无人机&#xff08;无人驾驶飞行器&#xff0c;UAV&#xff09;技术的快速发展&#xff0c;其在商业、娱乐和军事领域的广泛应用带来了新的安全挑战。特别是对于关键基础设施如电力系统&#xff0c;无人机的“黑飞”&…...

GitFlow 工作模式(详解)

今天再学项目的过程中遇到使用gitflow模式管理代码&#xff0c;因此进行学习并且发布关于gitflow的一些思考 Git与GitFlow模式 我们在写代码的时候通常会进行网上保存&#xff0c;无论是github还是gittee&#xff0c;都是一种基于git去保存代码的形式&#xff0c;这样保存代码…...

NPOI Excel用OLE对象的形式插入文件附件以及插入图片

static void Main(string[] args) {XlsWithObjData();Console.WriteLine("输出完成"); }static void XlsWithObjData() {// 创建工作簿和单元格,只有HSSFWorkbook,XSSFWorkbook不可以HSSFWorkbook workbook new HSSFWorkbook();HSSFSheet sheet (HSSFSheet)workboo…...