PythonForBeginners-中文系列教程-一-
PythonForBeginners 中文系列教程(一)
用 Python 逐行读取文本文件的 4 种方法
原文:https://www.pythonforbeginners.com/files/4-ways-to-read-a-text-file-line-by-line-in-python
在任何编程语言中,读取文件都是一项必要的任务。无论是数据库文件、图像还是聊天日志,读写文件的能力极大地增强了我们使用 Python 的能力。
在我们创建自动化有声读物阅读器或网站之前,我们需要掌握一些基本知识。毕竟,没有人在爬之前跑过。
更复杂的是,Python 提供了几种读取文件的解决方案。我们将讨论在 Python 中逐行读取文件的最常见的过程。一旦你掌握了用 Python 阅读文件的基本知识,你就能更好地应对未来的挑战。
您会很高兴地了解到 Python 提供了几个用于读取、写入和创建文件的函数。这些功能通过在幕后为我们处理一些工作来简化文件管理。
我们可以使用许多 Python 函数来逐行读取文件。
使用 readlines()方法逐行读取文件
我们在 Python 中读取文件的第一种方法是阻力最小的方法: readlines() 方法。这个方法将打开一个文件,并把它的内容分成几行。
该方法还返回文件中所有行的列表。我们可以使用 readlines()快速读取整个文件。
例如,假设我们有一个包含公司员工基本信息的文件。我们需要读取这个文件并对数据做些什么。
employees.txt
姓名:马库斯·盖伊
年龄:25
职业:网络开发员
姓名:莎莉雨
年龄:31
职业:高级程序员
示例 1:使用 readlines()读取文件
# open the data file
file = open("employees.txt")
# read the file as a list
data = file.readlines()
# close the file
file.close()
print(data)
输出
['Name: Marcus Gaye\n', 'Age: 25\n', 'Occupation: Web Developer\n', '\n', 'Name: Sally Rain\n', 'age: 31\n', 'Occupation: Senior Programmer\n']
readline()与 readlines()
与它的对应物不同, readline() 方法只返回文件中的一行。realine()方法还会在字符串末尾添加一个尾随换行符。
使用 readline()方法,我们还可以选择指定返回行的长度。如果没有提供大小,将读取整行。
考虑以下文本文件:
wise_owl.txt
一只聪明的老猫头鹰住在一棵橡树上。他越看越少说话。他说得越少,听得越多。为什么我们不能都像那只聪明的老鸟一样?
我们可以使用 readline()来获取文本文档的第一行。与 readlines()不同,当我们使用 readline()方法读取文件时,只打印一行。
示例 2:用 readline()方法读取一行
file = open("wise_owl.txt")
# get the first line of the file
line1 = file.readline()
print(line1)
file.close()
输出
A wise old owl lived in an oak.
readline()方法只检索单行文本。如果需要一次读取所有行,请使用 readline()。
file = open("wise_owl.txt")
# store all the lines in the file as a list
lines = file.readlines()
print(lines)
file.close()
输出
一只聪明的老猫头鹰住在橡树里。\n ','他越看越少说话。他说得越少,听到的越多。“为什么我们不能都像那只聪明的老鸟一样呢?\n"]
使用 While 循环读取文件
也可以使用循环来读取文件。使用我们在上一节中创建的同一个 wise_owl.txt 文件,我们可以使用 while 循环读取文件中的每一行。
示例 3:使用 while 循环和 readline()读取文件
file = open("wise_owl.txt",'r')
while True:
next_line = file.readline()
if not next_line:
break;
print(next_line.strip())
file.close()
输出
一只聪明的老猫头鹰住在橡树里。他越看越少说话。他说得越少,听到的越多。
为什么我们不能都像那只聪明的老鸟一样呢?
小心无限循环
在使用 while 循环时,需要注意一点。注意要为循环添加一个终止用例,否则你将永远循环下去。考虑下面的例子:
while True:
print("Groundhog Day!")
执行这段代码会导致 Python 陷入无限循环,打印“土拨鼠日”直到时间的尽头。当编写这样的代码时,总是要提供一种退出循环的方法。
如果你发现你不小心执行了一个无限循环,你可以在终端中点击键盘上的 Control+C 来逃离它。
在 Python 中读取文件对象
还可以使用 for 循环读取 Python 中的文件。例如,我们的客户给了我们以前客户的地址列表。我们需要使用 Python 来读取数据。
这是客户名单:
address_list.txt
山姆·加菲尔德边境路 9805 号。
新泽西州新不伦瑞克,邮编 08901
纽约林登赫斯特第二街 408 号
,邮编:11757
马库斯·盖伊
佛罗里达州洛克里奇市舒布农场街 622 号
,邮编 32955
普鲁登斯·布朗
明尼苏达州查斯卡市阿什利大街 66 号
邮编:55318
每当我们打开一个文件对象时,我们可以使用一个 for 循环,通过使用关键字中的来读取它的内容。使用关键字中的,我们可以循环遍历文件中的行。
示例 4:使用 for 循环读取文件中的行
# open the file
address_list = open("address_list.txt",'r')
for line in address_list:
print(line.strip())
address_list.close()
不幸的是,这个解决方案不适合我们的客户。数据采用 Python 列表的形式非常重要。在继续之前,我们需要将文件分成不同的地址,并将它们存储在一个列表中。
示例 5:读取文件并将内容拆分成一个列表
file = open("address_list.txt",'r')
address_list = []
i = 0
current_address = ""
for line in file:
# add a new address every three lines
if i > 2:
i = 0
address_list.append(current_address)
current_address = ""
else:
# add the line to the current address
current_address += line
i += 1
# use a for-in loop to print the list of addresses
for address in address_list:
print(address)
file.close()
使用上下文管理器读取文件
在任何编程语言中,文件管理都是一个微妙的过程。必须小心处理文件,以防损坏。当打开一个文件时,必须小心确保资源在以后被关闭。
而且在 Python 中一次可以打开多少文件是有限制的。为了避免这些问题,Python 为我们提供了上下文管理器。
用块引入
每当我们在 Python 中打开一个文件时,记住关闭它是很重要的。像 readlines()这样的方法对于小文件来说可以,但是如果我们有一个更复杂的文档呢?使用 Python 和语句将确保文件得到安全处理。
- with 语句用于安全地访问资源文件。
- Python 在遇到带有块的时会创建一个新的上下文。****
- 一旦块执行,Python 自动关闭文件资源。
- 上下文与 with 语句具有相同的范围。
让我们通过阅读一封保存为文本文件的电子邮件来练习使用 with 语句。
email.txt
尊敬的客户,
感谢您就您所购买产品的问题联系我们。我们渴望解决您对我们产品的任何疑虑。
我们想确保你对你的购买完全满意。为此,我们对所有库存提供 30 天退款保证。只需退回产品,我们将很乐意退还您的购买价格。
谢谢,
ABC 公司
`code example
# open file
with open("email.txt",'r') as email:
# read the file with a for loop
for line in email:
# strip the newline character from the line
print(line.strip())`
这次使用 for 循环来读取文件的行。当我们使用上下文管理器时,当文件的处理程序超出范围时,文件会自动关闭。当函数对文件完成时, with 语句确保资源得到负责任的处理。
摘要
我们已经介绍了在 Python 中逐行读取文件的几种方法。我们已经知道了 readline() 和readline()方法之间有很大的区别,我们可以使用 for 循环来读取 file 对象的内容。
我们还学习了如何使用带有语句的来打开和读取文件。我们看到了如何创建上下文管理器来使 Python 中的文件处理更加安全和简单。****
提供了几个例子来说明 Python 中各种形式的文件处理。花点时间研究这些示例,如果有不明白的地方,不要害怕尝试代码。
如果你想学习 Python 编程,请点击下面的链接,查看 Python 为初学者提供的更多精彩课程。
相关职位
- 使用 Python try except 处理错误
- 如何使用 Python 拆分字符串提高你的编码技能
- 使用 Python 字符串串联以获得更好的可读性
2019 年 5 款最佳 Python IDE 和代码编辑器
原文:https://www.pythonforbeginners.com/development/5-best-python-ides-and-code-editors-2019
比较 Python 的 5 大 ide 和文本编辑器
在本文中,我们将看看排名前 5 的 Python IDEs 和 5 个 Python 文本编辑器。
基于你的领域、价格和特性,你将会看到哪些 Python IDEs 和代码编辑器最适合你。
困惑于像 Eclipse 这样的 IDE,还是应该像 Sublime Text 这样简单的东西?我们什么都搞定了!
你将在这里学到什么:
顶级 Python IDEs 和文本编辑器比较
- 皮查姆
- Spyder
- PyDev
- 闲置的
- 翼
最佳 Python 代码编辑器
- 崇高的文本
- 原子
- 精力
- Visual Studio 代码
- Jupyter 笔记型电脑
顶级 Python IDEs 比较
| 集成驱动电子设备 | 费用 | 支持的操作系统 | 大小 | 大小(MB) | 支持的语言 | iPython 笔记本 |
| 皮查姆 | 199 美元/年 | Windows、MacOS、Linux | 大的 | 150-176 兆字节 | Python,Javascript,Coffescript,XML,HTML/XHTML,YAML,CSS,Saas,手写笔 | 不 |
| Spyder | 自由的 | Windows、MacOS、Linux | 大的 | 361-427MB | 计算机编程语言 | 是 |
| PyDev | 自由的 | Windows、MacOS、Linux | 大的 | 300MB | Python,C++,Coffeescript,HTML,Javascript,CSS | 是 |
| 闲置的 | 自由的 | Windows、MacOS、Linux | 小的 | 15.6 兆字节 | 计算机编程语言 | 不 |
| 翼 | 免费,付费 | Windows、MacOS、Linux | 大的 | 400 兆字节 | 计算机编程语言 | 是 |
顶级 Python IDEs 和文本编辑器比较
我们现在将深入了解每一个 ide 和文本编辑器。并且,我们将研究一些因素,这些因素将帮助您决定哪一个是 Python 的最佳 ide。
1。我的魅力在这里,我的魅力在这里,我的魅力在这里,我的魅力在这里,我的魅力在这里,我的魅力在这里,我的魅力在这里,我的魅力在这里,我的魅力在这里
价格:每位开发者每年 199 美元
支持的操作系统 : Windows、MacOS、Linux 发行版。

Source: Jetbrains
由 JetBrains 开发和维护的 PyCharm 是最流行的 Python IDE 之一。在 JetBrains 做的一项调查中,超过 20%的开发人员提到 Pycharm 是他们首选的 IDE。
作为一个 IDE,PyCharm 不仅仅允许您导入库和编写代码。它是一个专业级 IDE,允许 Python 开发人员编写生产级和可维护的代码。
使 PyCharm 成为最好的 Python IDE 的特性:
- 代码完成和自动错误检测
- 智能代码导航帮助您快速找到正确的类、文件、符号等
- 通过安全的重命名和删除使重构变得轻松。易于推动项目范围的变更
- 使用 Python profiler 轻松实现单元测试和图形用户界面测试
- 自动化部署 CI/CD 管道集成
- 数据库集成–Oracle、SQL Server、PostgreSQL 和其他主要数据库
- 远程开发——你可以用 PyCharm 的专业版编写你的 Python 代码。
PyCharm IDE 的利与弊
优点
- 像自动完成这样的智能特性可以帮助开发人员更快地编写代码
- PyCharm 支持多种框架
- 对于生产级过程高度可靠
缺点:
- 每位用户每年的成本约为 199 美元
- PyCharm 在 Windows 操作系统上存在某些性能问题
- PyCharm 有一个学习曲线
- 需要 SSD 和相当大的内存
2。Spyder Python IDE
价格:免费
支持的操作系统: Windows、MacOS、Linux

Source: Spyder.com
SPYDER 实际上是代表科学 PYthon 开发环境的首字母缩写。这个 IDE 主要由科学 Python 社区使用。
像 Numpy、Scipy、Matplotlib 等工具和库都内置在这个 Python IDE 中。专门为科学编程构建的强大功能使 Spyder 成为首选 IDE。它也是 Matlab 之外的科学程序员的最佳选择之一。
使 Spyder 成为科学编程最佳 IDE 的特性:
- 用于分析的集成 Pylint 和 Pyflakes
- 语法着色,断点
- 代码自动完成和变量资源管理器
- 附带了大多数科学编程库和框架
- iPython 笔记本集成
Spyder IDE 的优缺点:
优点
- 支持数据分析和可视化
- 利用自动完成和语法突出显示进行高效编程
- 帮助您利用 iPython notebook 对您的代码进行更精细的分析
- 实时代码分析和反馈
缺点
- 缺乏版本控制
- 缺少调试器的集成
3 .pydev ide〔t1〕
价格:免费
支持的操作系统: Windows、MacOS、Linux

Source: Pydev.org
PyDev 最初是一个主要用于 Eclipse 的 IDE,允许 Pythonista 在 Eclipse 上编写代码。但是,不,它已经扩展到 Eclipse 之外,现在还可以与 Visual Studio 代码集成。
虽然是免费的,PyDev 与 VS 代码的集成在 1 个月的免费试用后需要花费 40 美元。
使 PyDev 成为最佳 IDE 的特性:
- 其他 Python IDE 提供的所有基本自动完成特性
- 直接在 Eclipse 和 Visual Studio 代码中编辑代码
- Django 集成和单元测试的简易性
PyDev IDE 的利与弊
优点
- 开放源码
- 皮林特集成
- 调试器和实时
缺点
- 由于 it 众筹,支持有限
- 比其他企业支持的 ide 功能少
4.Python 空闲
价格:免费
支持的操作系统: Windows、MacOS、Linux

下载 Python 后,Python 包中默认提供 Python IDLE。对于初级 Python 程序员来说,这是一个很好的 IDE,因为在所有操作系统上设置它都非常容易。
它绝对免费使用。但是,它还不足以创建高级的生产级 Python 代码。
使 IDLE 成为最好的 Python 初学者 IDE 的特性:
- 易于安装,几乎不需要任何工作
- IDLE 是跨平台的,这意味着它可以在所有三种操作系统上支持你
- 多窗口代码编辑器,支持智能缩进、自动完成等功能
Python IDLE 的利弊
优点:
- 易于设置 Python IDE,对初学者友好
- 具有较小的整体 IDE 尺寸
- 不适合做大型项目
缺点:
- 没有多语言支持
- 缺少错误标记功能
- Python 代码没有集成调试
5。Wing Python IDE
价格::教育工作者 45 美元,专业许可证每位用户 99 美元
支持的操作系统: Windows、MacOS、Linux

Wing 是一个更快、更稳定、非常轻量级的 Python IDE,并且经常被拿来与 PyCharm 比较。从负担得起的订阅选项到众多功能,这是每个 PyCharm 用户都应该看看的 IDE。
使 Wing 成为专业 Python 开发人员首选之一的特性:
- 类型化集成和代码警告
- 类似于 PyCharm 的远程调试
- 拆分重用策略
- 皮林特集成
- 使用 Python 3 支持类型注释
Wing Python IDE 的利与弊:
优点:
- 远程开发使得 Python 开发人员使用 Wing 变得更加容易
- TDD 的众多集成
- 自动完成、实时错误警告等
- 非常快,这意味着它不会妨碍开发人员的工作效率
缺点:
- 比 PyCharm 等其他专业级 Python IDEs 的功能少
最佳 Python 代码编辑器
与 IDE 不同,Python 代码编辑器只是允许您编写代码的简单程序。使用这些代码编辑器,您可以导入库、框架和编写代码。
尽管我们经历了这些 ide,Python 代码编辑器也有自己的位置。没有 Python 中的代码编辑器,大多数开发人员不会学习或理解语法和代码片段。
所以,我们来看看顶级的 Python 代码编辑器都有哪些。
1。崇高的文字
费用:80 美元
支持的操作系统 : Windows、Linux 和 MacOS
崇高截图

资料来源:Sublimetext.com
Sublime Text 是类代码编辑器中最好的,它速度极快,允许开发人员编写自己的插件。它拥有多行编辑、块编辑、正则表达式搜索等众多特性,绝对是 Python 开发者的顶级代码编辑器之一。
2。Atom Python 代码编辑器
费用:免费
支持的操作系统 : Windows、Linux 和 MacOS
Atom 是最早发布的代码编辑器之一。它有它的吸引力,但在 Python 社区的其他代码编辑器中不再占有重要的份额。大多数代码编辑器带来的优势是代码编辑器更快。但是,Atom 比大多数其他代码编辑器要慢得多。
3。Vim Python 代码编辑器
费用:免费
支持的操作系统 : Windows、Linux 和 MacOS
Vim 截图

资料来源:Spacevim.org
Vim 在很大程度上是一个命令行界面代码编辑器,但它也可以作为一个独立的应用程序工作。除此之外,VIM 速度快,跨平台,性能极高。
虽然 Vim 作为文本编辑器有其优势,但它肯定不是初学者的首选。一边学 Python 一边学 Vim就像同时学两件事。如果您是一名经验丰富的开发人员,您会发现使用 Vim 比初级 Python 开发人员更有效率。
4。Visual Studio 代码
费用:免费
支持的操作系统 : Windows、Linux 和 MacOS
Visual Studio Screeshot

Source: Visualstudio.com
Visual Studio(VS)代码由微软开发,于 2015 年发布。它可以免费下载。
VS 代码编辑器支持 Python 片段、语法高亮、括号匹配和代码折叠。
5。Jupyter 笔记型电脑
费用:免费
支持的操作系统 : Windows、Linux 和 MacOS
Jupyter 屏幕截图

Source: Jupyter.org
Jupyter 笔记本是科学计算和数据专家最喜欢的 Python 编辑器。如果你的工作涉及数据探索、研究和演示,Jupyter 是最好的。
您可以将笔记本保存为 JSON 格式,或者将结果导出为 PDF 和 HTML 格式。
Python IDEs 和代码编辑器常见问题
Python IDE 和 Python 代码编辑器有什么区别?
Python 代码编辑器是简单的界面,允许您编写程序或 Python 程序的模块。除了编写程序和突出语法之外,代码编辑器的功能非常有限。
另一方面,ide 允许你做任何事情——编写代码、调试、版本控制和其他一切让你的工作达到专业水平的事情。从编写代码到将您的工作与 CI/CD 流程集成,IDE 可以帮助您完成所有工作。
2019 年最好的 Python IDE 是什么?
这取决于你的用例。理想情况下,每个 IDE 都有自己的优点和缺点。例如,如果您需要将远程部署作为一项功能,可以考虑 PyCharm。但是,如果你是一名数据专家,你可能想探索 Spyder 的特性。
Python 中数字的绝对值
原文:https://www.pythonforbeginners.com/basics/absolute-value-of-a-number-in-python
在 python 中处理数字时,我们需要比较两个数字的大小,而不考虑它们的符号。例如,量值-10 大于量值 1。但是当比较-10 和 1 时,由于 1 的正号,它被声明为更大的数字。为了比较这两个数字的大小,首先我们需要找到这两个数字的绝对值。然后我们可以通过比较绝对值来比较数字的大小。在本文中,我们将用 python 实现程序来寻找不同的数字数据类型的绝对值。
Python 中如何计算一个数的绝对值?
我们可以使用 abs()函数在 python 中计算任意数字的绝对值。abs()函数将一个数字作为唯一的参数,并返回该数字的绝对值。
输入参数可以是浮点数、整数或复数。我们还可以传递一个二进制数、一个八进制数或一个十六进制数作为 abs()函数的输入。
我们可以从下一节的例子中理解 abs()函数的工作原理。
Python 中使用 abs()函数的示例
我们可以使用 abs()函数找到一个整数的绝对值,如下所示。
myNum=10
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
myNum=-10
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
输出:
Absolute value of 10 is 10.
Absolute value of -10 is 10.
我们可以使用 abs()函数找到浮点数的绝对值,如下所示。
myNum=10.5
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
myNum=-10.5
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
输出:
Absolute value of 10.5 is 10.5.
Absolute value of -10.5 is 10.5.
如果我们想知道一个复数的大小,我们可以使用 abs()函数。abs()函数接受一个复数作为输入,并返回该复数的大小,如下所示。
myNum=3+5j
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
输出:
Absolute value of (3+5j) is 5.830951894845301.
如果一个数以二进制、八进制或十六进制表示,我们也可以使用 abs()函数来确定十进制数的绝对值,如下所示。
#hexadecimal number
myNum=0x123
absoluteVal=abs(myNum)
print("Absolute value {} is {}.".format(myNum,absoluteVal))
#binary number
myNum=0b1001
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
#octal number
myNum=0o123
absoluteVal=abs(myNum)
print("Absolute value of {} is {}.".format(myNum,absoluteVal))
输出:
Absolute value 291 is 291.
Absolute value of 9 is 9.
Absolute value of 83 is 83.
绝对值计算过程中的错误处理
Python 是一种具有动态类型的编程语言。这意味着 python 解释器在运行时确定变量的数据类型。因此,当我们将一个变量作为输入传递给 abs()函数时,它可能没有正确数据类型的值来产生正确的输出。例如,当我们将一个字符串作为输入参数传递给 abs()函数时,该函数将引发一个 TypeError 异常,如下所示。
myNum="PFB"
absoluteVal=abs(myNum)
print("Absolute value {} is {}.".format(myNum,absoluteVal))
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/main.py", line 2, in <module>
absoluteVal=abs(myNum)
TypeError: bad operand type for abs(): 'str'
我们知道,当程序的任何部分出现异常时,程序会立即终止。这将导致写入文件的数据或程序中执行的任何重要计算丢失。我们可以通过使用 python try except 块进行异常处理来避免这种损失。每当我们将一个类型不正确的变量作为输入参数传递给函数时,abs()函数都会引发一个异常。如果需要,我们可以在 except 块中处理异常,保存必要的数据并关闭文件。
结论
在本文中,我们学习了如何使用 python 中的 abs()函数来计算数字的绝对值。我们还研究了如何在十进制中求二进制、八进制和十六进制中数的绝对值。最后,我们看到了如何使用 try except 块处理 abs()函数生成的任何异常。请继续关注更多内容丰富的文章。
用 Python 向字典中添加项目
原文:https://www.pythonforbeginners.com/dictionary/add-an-item-to-a-dictionary-in-python
python 中的字典是一种以键值对形式存储数据的数据结构。键值对也称为项目。每个字典中的键值对由冒号“:”分隔,字典中的每个条目由逗号“,”分隔。在本文中,我们将研究用 python 向字典添加条目的不同方法。
使用下标符号将项目添加到词典中
如果我们有一个名为myDict的字典和一个值为myKey和myValue的键值对,那么我们可以使用语法myDict [ myKey ] = myValue将键值对添加到字典中。这可以如下进行。
myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
myDict["niche"] = "programming"
print("Modified Dictionary is:", myDict)
输出:
Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
在上面的例子中,我们已经添加了一个新的关键字“利基”,它具有与之相关的值“编程”。
请记住,如果要添加到字典中的条目的键已经存在,则该键的值将被新值覆盖。这可以从下面的例子中看出。
myDict = {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
print("Original Dictionary is:", myDict)
myDict["niche"] = "python programming"
print("Modified Dictionary is:", myDict)
输出:
Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'python programming'}
在上面的例子中,关键字“niche”已经存在于字典中,其值为“programming”。当我们尝试添加以“niche”作为键,以“python 编程”作为关联值的键-值对时,与“niche”关联的值被更新为新值。
使用 Python 中的 update()方法将项目添加到字典中
我们可以使用 update()方法向字典中添加一个条目。在字典上调用 update()方法时,它将字典或具有键值对的 iterable 对象作为输入,并将条目添加到字典中。
我们可以给一个新的字典作为 update()方法的输入,并将条目添加到给定的字典中,如下所示。
myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
myDict.update({'niche': 'programming'})
print("Modified Dictionary is:", myDict)
输出:
Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
我们可以给出一个包含键-值对的元组列表作为 update()方法的输入,并向给定的字典添加条目,如下所示。
myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
items = [("niche", "programming")]
myDict.update(items)
print("Modified Dictionary is:", myDict)
输出:
Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
我们还可以将键值对作为关键字参数传递给 update()方法,以便向字典中添加元素。这里,键将被用作关键字参数,值将被分配为关键字参数的输入,如下所示。
myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
myDict.update(niche="programming")
print("Modified Dictionary is:", myDict)
输出:
Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
使用 Python 中的**运算符将项目添加到字典中
双星号()运算符用于向函数传递可变长度的关键字参数。我们还可以使用操作符将一个键值对添加到另一个字典中。当我们将**操作符应用于字典时,它会反序列化字典并将其转换为键值对的集合。这个键值对的集合可以再次转换成字典。
要将一个条目添加到字典中,我们将首先创建一个只包含该条目的字典。然后,我们将使用**操作符合并新字典和必须添加条目的字典,如下所示。
myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
newDict = {'niche': 'programming'}
myDict = {**myDict, **newDict}
print("Modified Dictionary is:", myDict)
输出:
Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
使用 setitem()方法将项目添加到词典中
我们还可以使用 setitem()方法向字典中添加一个条目。在字典上调用 setitem()方法时,它将新的键和值分别作为第一个和第二个参数,并将键-值对添加到字典中,如下所示。
myDict = {"name": "PythonForBeginners", "acronym": "PFB"}
print("Original Dictionary is:", myDict)
myDict.__setitem__('niche', 'programming')
print("Modified Dictionary is:", myDict)
输出:
Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
如果字典中已经存在该键,则与它关联的值将被新值覆盖。这可以从下面的例子中看出。
myDict = {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
print("Original Dictionary is:", myDict)
myDict.__setitem__('niche', 'python programming')
print("Modified Dictionary is:", myDict)
输出:
Original Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'programming'}
Modified Dictionary is: {'name': 'PythonForBeginners', 'acronym': 'PFB', 'niche': 'python programming'}
结论
在本文中,我们看到了用 python 向字典添加条目的不同方法。要阅读更多关于 python 中字典的内容,你可以阅读这篇关于字典理解的文章或者这篇关于如何在 python 中合并两个字典的文章。
用 Python 在数据帧中追加新行
原文:https://www.pythonforbeginners.com/basics/append-a-new-row-in-a-dataframe-in-python
为了在 python 中处理表格数据,我们通常使用 dataframes。在本文中,我们将讨论如何在数据帧中追加新行。
使用 loc[]属性在数据帧中追加新行
如果我们有一个列表形式的行,我们可以使用 pandas 模块中定义的 loc[]属性将该行添加到 dataframe 中。loc 属性用于获取数据帧中特定位置的行。当在数据帧上调用时,它将行号作为方括号内的输入,并返回数据帧的一部分。
为了将列表作为新行添加到数据帧中,我们将把列表分配给数据帧最后一行的片。
要获得数据帧中最后一行的位置,我们可以使用 len()函数来确定数据帧的长度。获得数据帧的长度后,我们可以将列表作为新行添加到数据帧中,如下所示。
import pandas as pd
df = pd.read_csv('Demo.csv')
print("The dataframe before the append operation:")
print(df)
values = [10, "Sam", "Typescript"]
length = len(df)
df.loc[length] = values
print("The dataframe after the append operation:")
print(df)
输出:
The dataframe before the append operation:
Roll Name Language
0 1 Aditya Python
1 2 Sam Java
2 3 Chris C++
The dataframe after the append operation:
Roll Name Language
0 1 Aditya Python
1 2 Sam Java
2 3 Chris C++
3 10 Sam Typescript
在这种方法中,我们将一个列表作为新行添加到数据帧中。现在,让我们讨论一种将 python 字典附加到数据帧的方法。
使用 Append()方法在数据帧中追加新行
如果给我们一个字典,其中字典的键由数据帧的列名组成,我们可以使用append()方法将字典作为一行添加到数据帧中。在 dataframe 上调用 append()方法时,该方法将 python 字典作为其输入参数,并将字典的值追加到 dataframe 的最后一行。另外,我们需要将值 True 赋给 dataframe 的 ignore_index 参数。执行后,append()方法返回更新后的数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
df = pd.read_csv('Demo.csv')
print("The dataframe before the append operation:")
print(df)
valueDict = {'Roll': 15, 'Name': "Wilson", 'Language': "Golang"}
length = len(df)
df = df.append(valueDict, ignore_index=True)
print("The dataframe after the append operation:")
print(df)
输出:
The dataframe before the append operation:
Roll Name Language
0 1 Aditya Python
1 2 Sam Java
2 3 Chris C++
The dataframe after the append operation:
Roll Name Language
0 1 Aditya Python
1 2 Sam Java
2 3 Chris C++
3 15 Wilson Golang
结论
在本文中,我们讨论了用 python 在数据帧中追加新行的两种方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于用 python 理解字典的文章。
用 Python 将字典附加到 CSV 文件
原文:https://www.pythonforbeginners.com/basics/append-dictionary-to-csv-file-in-python
CSV 文件是存储结构化表格数据的最有效工具之一。有时,我们可能需要从 python 字典中向 CSV 文件追加数据。在本文中,我们将讨论如何用 python 将字典中的值追加到 CSV 文件中。
使用 csv.writer()将字典附加到 CSV 文件
您可以使用CSV.writer()方法和CSV.writerow() 方法将字典附加到 CSV 文件。为此,我们将首先使用open() 函数在追加模式下打开 CSV 文件。open()函数将文件名作为其第一个输入参数,将文字“a”作为其第二个输入参数,以表示该文件是以追加模式打开的。
打开文件后,我们将使用CSV.writer()函数创建一个 CSV writer 对象。CSV.writer()函数将包含 CSV 文件的 file 对象作为其输入参数,并返回一个 writer 对象。
创建 writer 对象后,我们将使用w riterow()方法将字典附加到 CSV 文件中。在 writer 对象上调用writerow()方法时,该方法将字典中的值作为其输入参数,并将其附加到 CSV 文件中。
在执行了writerow()方法之后,您必须使用close() 方法关闭 CSV 文件。否则,更改不会保存在 CSV 文件中。下面给出了这种向 CSV 文件添加字典的方法的源代码。
import csv
myFile = open('Demo.csv', 'r+')
print("The content of the csv file before appending is:")
print(myFile.read())
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
writer = csv.writer(myFile)
writer.writerow(myDict.values())
myFile.close()
myFile = open('Demo.csv', 'r')
print("The content of the csv file after appending is:")
print(myFile.read())
输出:
The content of the csv file before appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the csv file after appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
4,Joel,Golang
使用 csv 将字典附加到 CSV 文件。词典作者()
不使用csv.writer()方法,我们可以使用csv.DictWriter()函数和csv.writerow() 方法将 python 字典附加到 csv 文件中。该方法几乎类似于使用csv.writer()方法的方法,但有以下区别。
- 我们将使用
csv.DictWriter()方法,而不是csv.writer()方法。DictWriter()方法将包含 csv 文件的 file 对象作为其输入参数,并返回一个 DictWriter 对象。 - 当在 DictWriter 对象上执行
writerow()方法时,它将一个字典作为输入参数,而不是字典中的值。
使用csv.DictWriter() 将字典附加到 csv 文件的 python 代码如下。
import csv
myFile = open('Demo.csv', 'r+')
print("The content of the csv file before appending is:")
print(myFile.read())
myDict = {'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
print("The dictionary is:")
print(myDict)
writer = csv.DictWriter(myFile, fieldnames=list(myDict.keys()))
writer.writerow(myDict)
myFile.close()
myFile = open('Demo.csv', 'r')
print("The content of the csv file after appending is:")
print(myFile.read())
输出:
The content of the csv file before appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
The dictionary is:
{'Roll': 4, 'Name': 'Joel', 'Language': 'Golang'}
The content of the csv file after appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
4,Joel,Golang
结论
在本文中,我们讨论了用 python 向 csv 文件添加字典的两种方法。在这些方法中,将追加字典,而不管它与 csv 文件中的列相比是否具有相同的项目数,或者它与 csv 文件中的列名相比是否具有相同的键。因此,它建议确保字典应该具有与 csv 文件中的列相同数量的键。您还应该确保 csv 文件的列顺序应该与字典中的键顺序相同。否则,附加到 csv 文件的数据将变得不一致,并会导致错误。
我希望你喜欢阅读这篇文章。想了解更多 python 中的字典,可以阅读这篇关于 python 中的字典理解的文章。你也可以用 python 写这篇关于列表理解的文章。
请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中将字典追加到数据帧
原文:https://www.pythonforbeginners.com/basics/append-dictionary-to-dataframe-in-python
我们使用 python 字典来存储键值对。类似地,数据帧用于以表格格式存储包含与关键字相关联的值的记录。在本文中,我们将讨论如何在 Python 中将字典附加到数据帧中。
如何在 Python 中给数据帧追加字典?
为了给一个熊猫数据帧添加一个字典,我们将使用append()方法。在 dataframe 上调用append() 方法时,该方法将一个字典作为其输入参数,并返回一个新的 dataframe。append()方法也将值True作为其ignore_index参数的输入变量。
输出数据帧包含作为原始数据帧中的一行追加的字典值。您可以在下面的示例中观察到这一点。
import pandas as pd
names=pd.read_csv("name.csv")
print("The input dataframe is:")
print(names)
myDict={"Class":3, "Roll":22, "Name":"Sakshi"}
print("The dictionary is:")
print(myDict)
names=names.append(myDict,ignore_index=True)
print("The output dataframe is:")
print(names)
输出
The input dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 2 1 Joel
4 2 22 Tom
5 2 44 Samantha
6 3 33 Tina
7 3 34 Amy
The dictionary is:
{'Class': 3, 'Roll': 22, 'Name': 'Sakshi'}
The output dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 2 1 Joel
4 2 22 Tom
5 2 44 Samantha
6 3 33 Tina
7 3 34 Amy
8 3 22 Sakshi
如果字典的键数少于数据帧中指定的列数,则在字典所附加的行中,剩余的列被赋予值NaN。您可以在下面的示例中观察到这一点。
import pandas as pd
names=pd.read_csv("name.csv")
print("The input dataframe is:")
print(names)
myDict={"Class":3, "Name":"Sakshi"}
print("The dictionary is:")
print(myDict)
names=names.append(myDict,ignore_index=True)
print("The output dataframe is:")
print(names)
输出:
The input dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 2 1 Joel
4 2 22 Tom
5 2 44 Samantha
6 3 33 Tina
7 3 34 Amy
The dictionary is:
{'Class': 3, 'Name': 'Sakshi'}
The output dataframe is:
Class Roll Name
0 1 11.0 Aditya
1 1 12.0 Chris
2 1 13.0 Sam
3 2 1.0 Joel
4 2 22.0 Tom
5 2 44.0 Samantha
6 3 33.0 Tina
7 3 34.0 Amy
8 3 NaN Sakshi
如果字典不具有与数据帧中的列相同的关键字,则为数据帧中不存在的每个关键字添加一个新列作为列名。向字典追加与列名不同的键值时,现有行中新列的值被填充为NaN。类似地,不存在于字典中但存在于数据帧中的列被赋予值NaN,即字典被附加到的行。您可以在下面的例子中观察到这一点。
import pandas as pd
names=pd.read_csv("name.csv")
print("The input dataframe is:")
print(names)
myDict={"Class":3, "Roll":22, "Name":"Sakshi","Height":160}
print("The dictionary is:")
print(myDict)
names=names.append(myDict,ignore_index=True)
print("The output dataframe is:")
print(names)
输出:
The input dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 2 1 Joel
4 2 22 Tom
5 2 44 Samantha
6 3 33 Tina
7 3 34 Amy
The dictionary is:
{'Class': 3, 'Roll': 22, 'Name': 'Sakshi', 'Height': 160}
The output dataframe is:
Class Roll Name Height
0 1 11 Aditya NaN
1 1 12 Chris NaN
2 1 13 Sam NaN
3 2 1 Joel NaN
4 2 22 Tom NaN
5 2 44 Samantha NaN
6 3 33 Tina NaN
7 3 34 Amy NaN
8 3 22 Sakshi 160.0
要将两个或更多字典或一个字典列表追加到数据帧中,可以使用 for 循环和append()方法。在 for 循环中,可以将每个字典追加到数据帧中。
建议阅读:如果你对机器学习感兴趣,你可以阅读这篇关于 k-prototypes 聚类的文章,并给出数值示例。你可能也会喜欢这篇关于数据油墨比率的文章。
在不久的将来,append()方法将被弃用。因此,您可以使用 pandas concat() 方法向 dataframe 添加一个字典,如下所示。
import pandas as pd
names=pd.read_csv("name.csv")
print("The input dataframe is:")
print(names)
myDict={"Class":3, "Roll":22, "Name":"Sakshi","Height":160}
print("The dictionary is:")
print(myDict)
tempDf=pd.DataFrame([myDict])
names=pd.concat([names,tempDf],ignore_index=True)
print("The output dataframe is:")
print(names)
输出:
The input dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 2 1 Joel
4 2 22 Tom
5 2 44 Samantha
6 3 33 Tina
7 3 34 Amy
The dictionary is:
{'Class': 3, 'Roll': 22, 'Name': 'Sakshi', 'Height': 160}
The output dataframe is:
Class Roll Name Height
0 1 11 Aditya NaN
1 1 12 Chris NaN
2 1 13 Sam NaN
3 2 1 Joel NaN
4 2 22 Tom NaN
5 2 44 Samantha NaN
6 3 33 Tina NaN
7 3 34 Amy NaN
8 3 22 Sakshi 160.0
结论
在本文中,我们讨论了如何在 python 中将字典附加到数据帧中。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
用 Python 将列表追加到 CSV 文件中
原文:https://www.pythonforbeginners.com/basics/append-list-to-csv-file-in-python
列表是 python 中最常用的数据结构之一。在本文中,我们将讨论如何在 python 中向 CSV 文件追加列表。
使用 csv.writer()在 Python 中将列表追加到 CSV 文件中
csv 模块为我们提供了对 CSV 文件执行各种操作的不同方法。要在 python 中将一个列表附加到 csv 文件中,我们可以使用 c sv.writerow()方法和csv.writer()方法。为此,我们将使用以下步骤。
- 首先,我们将使用
open()函数在追加模式下打开一个 csv 文件。open()函数将文件名作为第一个输入参数,将文字“a”作为第二个输入参数,以表明文件将以追加模式打开。它返回一个 file 对象,包含由open()函数打开的 csv 文件。 - 打开文件后,我们将使用
csv.writer()方法创建一个csv.writer对象。csv.writer()方法将 file 对象作为输入参数,并返回一个 writer 对象。一旦创建了 writer 对象,我们就可以使用csv.writerow()方法将列表附加到 csv 文件中。 - 在 writer 对象上调用
csv.writerow()方法时,该方法将一个列表作为其输入参数,并将其附加到 writer 对象引用的 csv 文件中。我们将把这个列表作为输入参数传递给writerow()方法。
在执行writerow()方法后,列表将被附加到 CSV 文件中。为了保存数据,您应该使用close()方法关闭文件。否则,不会将任何更改保存到 csv 文件中。
使用 csv.writer()方法将列表追加到 csv 文件的源代码如下。
import csv
myFile = open('Demo.csv', 'r+')
print("The content of the csv file before appending is:")
print(myFile.read())
myList = [4, 'Joel','Golang']
print("The list is:")
print(myList)
writer = csv.writer(myFile)
writer.writerow(myList)
myFile.close()
myFile = open('Demo.csv', 'r')
print("The content of the csv file after appending is:")
print(myFile.read())
输出:
The content of the csv file before appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
The list is:
[4, 'Joel', 'Golang']
The content of the csv file after appending is:
Roll,Name,Language
1,Aditya,Python
2,Sam, Java
3, Chris, C++
4,Joel,Golang
结论
在本文中,我们讨论了在 python 中向 csv 文件添加列表的方法。在这种方法中,列表将被附加到 csv 文件中,而不管它与 csv 中的列相比是否具有相同数量的元素。因此,建议确保每个列表与 csv 文件中的列相比具有相同数量的元素。此外,您应该确保列表中元素的顺序应该与 csv 文件中的列一致。否则,附加到 csv 文件的数据将变得不一致,并会导致错误。
要了解更多关于 python 中的列表,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
用 Python 向文件追加文本
原文:https://www.pythonforbeginners.com/basics/append-text-to-file-in-python
在进行文件操作时,我们可能需要在不删除现有数据的情况下向现有文件添加文本。在本文中,我们将讨论如何在 python 中向文件追加文本。
使用 write()方法将文本追加到文件中
要使用write()方法将文本添加到文件中,我们首先需要在 append 模式下打开文件。为此,我们将使用open()函数,将文件名作为第一个参数,将“r+”作为第二个参数。打开文件后,我们可以使用write()方法简单地将文本添加到文件中。在 file 对象上调用write()方法,并将需要追加到文件中的文本作为其输入参数。你可以在下面观察整个过程。
myFile = open("sample.txt", mode="r+")
print("The content of the file before modification is:")
text = myFile.read()
print(text)
myString = "This string will be appended to the file."
myFile.write(myString)
myFile.close()
myFile = open("sample.txt", "r")
print("The content of the file after modification is:")
text = myFile.read()
print(text)
输出:
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.This string will be appended to the file.
将文本附加到文件后,不要忘记关闭文件。否则,内容将不会被保存。这里,我们使用了 read()函数来验证附加文本前后的文件内容。
使用 print()函数将文本添加到文件中
通常,当我们使用print()函数时,它会将值打印到标准输入中。然而,我们也可以使用print()函数在 python 中将文本追加到文件中。print()函数有一个可选参数“file”。使用这个参数,我们可以指定在哪里打印作为输入传递给print()函数的值。
为了将文本追加到文件中,我们将首先使用open()函数在追加模式下打开文件。之后,我们将把文本和文件对象分别作为第一个和第二个输入参数传递给打印函数。执行print()功能后,文本将被附加到文件中。
myFile = open("sample.txt", mode="r+")
print("The content of the file before modification is:")
text = myFile.read()
print(text)
myString = "This string will be appended to the file."
print(myString, file=myFile)
myFile.close()
myFile = open("sample.txt", "r")
print("The content of the file after modification is:")
text = myFile.read()
print(text)
输出:
The content of the file before modification is:
This is a sample file.
The content of the file after modification is:
This is a sample file.
This string will be appended to the file.
在输出中,您可以观察到myString已经被追加到文件的新行中。当我们使用write()方法做同样的操作时,myString被附加到现有文件的最后一行。因此,您可以利用这种差异根据您的需求选择合适的方法。此外,请确保在向文件追加文本后关闭该文件。否则,将不会保存更改。
结论
在本文中,我们讨论了用 python 向文件追加文本的两种方法。要了解更多关于文件操作的信息,您可以阅读这篇关于 python 中的文件处理的文章。你可能也会喜欢这篇关于用 python 理解列表的文章。
下载教程
原文:https://www.pythonforbeginners.com/argparse/argparse-tutorial
这是什么?
命令行选项、参数和子命令的解析器
为什么要用?
argparse 模块使得编写用户友好的命令行界面变得容易。
它是怎么做到的?
该程序定义了它需要什么参数,argparse 将计算出如何从 sys.argv 中解析这些参数,argparse 模块还会自动生成帮助和用法消息,并在用户向程序提供无效参数时发出错误消息。
概念
当您在没有任何选项的情况下运行“ls”命令时,它将默认显示当前目录的内容。如果您在当前所在的不同目录上运行“ls”,您应该键入“ls directory_name”。
“目录名”是一个“位置参数”,这意味着程序知道如何处理这个值。
要获得关于文件的更多信息,我们可以使用“-l”开关。
“-l”被称为“可选参数”。如果您想显示 ls 命令的帮助文本,可以键入“ls–help”
抱怨吗
要开始使用 argparse 模块,我们首先必须导入它。
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
运行代码
使用–help 选项运行代码(不使用任何选项运行脚本将不会在 stdout 中显示任何内容)
python program.py --help (or python program.py -h)
usage: program.py [-h]
optional arguments:
-h, --help show this help message and exit
正如上面所看到的,即使我们没有在脚本中指定任何帮助参数,它仍然给了我们一个很好的帮助信息。这是我们唯一免费的选择。
位置参数
在上面的“ls”示例中,我们使用了位置参数“ls directory_name”。每当我们想要指定程序将接受哪个命令行选项时,我们使用“add_argument()”方法。
parser.add_argument("echo") # naming it "echo"
args = parser.parse_args() # returns data from the options specified (echo)
print(args.echo)
如果我们现在运行代码,我们可以看到它要求我们指定一个选项
$ python program.py
usage: program.py [-h] echo
program.py: error: too few arguments
当我们指定回声选项时,它将显示“回声”
$ python program.py echo
echo
#Using the --help option
$ python program.py --help
usage: program.py [-h] echo
positional arguments:
echo
optional arguments:
-h, --help show this help message and exit
扩展帮助文本
为了获得关于我们的位置论点(echo)的更多帮助,我们必须改变我们的脚本。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo)
导致以下结果:
$ python program.py --help
usage: program.py [-h] echo
positional arguments:
echo echo the string you use here
optional arguments:
-h, --help show this help message and exit
注意:Argparse 将我们给出的选项视为一个字符串,但是我们可以改变它。
运行类型设置为整数的代码
这段代码将把输入视为一个整数。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
type=int)
args = parser.parse_args()
print(args.square**2)
如果我们使用–help 选项运行程序,我们可以看到:
$ python program.py -h
usage: program.py [-h] square
positional arguments:
square display a square of a given number
optional arguments:
-h, --help show this help message and exit
运行程序
从帮助文本中,我们可以看到,如果我们给程序一个数字,它会把方块还给我们。
酷,让我们试试吧:
$ python program.py 4
16
$ python program.py 10
100
如果我们使用字符串而不是数字,程序将返回一个错误
$ python program.py four
usage: program.py [-h] square
program.py: error: argument square: invalid int value: 'four'
可选参数
在上面的“ls”示例中,我们使用了可选参数“-l”来获取关于文件的更多信息。当指定了–verbosity 时,下面的程序将显示一些内容,而当没有指定时,则不显示任何内容。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
if args.verbose:
print("verbosity turned on")
可选参数(或选项)在不使用时(默认情况下)被赋予 None 值。使用–verbosity 选项,实际上只有两个值是有用的,True 或 False。
关键字“action”被赋予值“store_true ”,这意味着如果指定了该选项,则将值“true”赋给 args,verbose 不指定该选项意味着 False。
如果我们使用–help 选项运行程序,我们可以看到:
$ python program.py -h
usage: program.py [-h] [--verbose]
optional arguments:
-h, --help show this help message and exit
--verbose increase output verbosity
使用–verbose 选项运行程序
$ python program.py --verbose
verbosity turned on
排序选项
使用这些选项的简短版本非常简单:
parser.add_argument("-v", "--verbose", help="increase output verbosity",
action="store_true")
帮助文本将用简短版本更新。
来源
[http://docs.python.org/dev/library/argparse.html](https://docs.python.org/dev/library/argparse.html "argparse")
Python 中的算术序列
原文:https://www.pythonforbeginners.com/basics/arithmetic-sequence-in-python
你可能在数学课上听说过算术数列和几何数列。在这篇文章中,我们将讨论算术序列。我们还将在 Python 中实现对算术序列执行不同操作的程序。
什么是等差数列?
一个算术序列是一个数列,其中任何两个连续的数字有一个固定的差异。这种差异也称为等差数列中各项之间的共同差异。
例如,3,5,7,9,11,13,…是一个连续项之间的普通差为 2 的算术序列。
算术数列中的第 n 项
如果给我们第一项 A ₁ 和公差带 D,我们可以把第二项写成A₁+D,第三项写成 A₁+2D,第四项写成A₁+3D,以此类推。第 N 项将被写成A₁+(N-1)D为了在 python 中找到一个等差序列的第 N 项,我们可以简单地用一个 for 循环将第一项 A ₁ 加上公差(N-1)倍,如下所示。
commonDifference = 2
print("Common Difference in the arithmetic sequence is:", commonDifference)
firstTerm = 3
print("First term in the arithmetic sequence is:", firstTerm)
# calculating 100th term
N = 100
nthTerm = firstTerm
for i in range(1, N):
nthTerm = nthTerm + commonDifference
print("100th term in the arithmetic sequence is:", nthTerm)
输出:
Common Difference in the arithmetic sequence is: 2
First term in the arithmetic sequence is: 3
100th term in the arithmetic sequence is: 201
或者,我们可以使用以下公式直接计算第 n 项。
commonDifference = 2
print("Common Difference in the arithmetic sequence is:", commonDifference)
firstTerm = 3
print("First term in the arithmetic sequence is:", firstTerm)
# calculating 100th term
N = 100
nthTerm = firstTerm + (N - 1) * commonDifference
print("100th term in the arithmetic sequence is:", nthTerm)
输出:
Common Difference in the arithmetic sequence is: 2
First term in the arithmetic sequence is: 3
100th term in the arithmetic sequence is: 201
Python 中算术序列中 N 项的和
要计算算术表达式中 N 项的总和,我们可以使用 for 循环简单地将每一项相加。在 for 循环中,我们将首先使用上面讨论的公式找到每一项。之后,我们将每个项相加,计算 N 项之和,如下所示。
commonDifference = 2
print("Common Difference in the arithmetic sequence is:", commonDifference)
firstTerm = 3
print("First term in the arithmetic sequence is:", firstTerm)
# calculating sum of 50 terms
N = 50
sumOfTerms = 0
for i in range(1, N + 1):
ithTerm = firstTerm + (i - 1) * commonDifference
sumOfTerms = sumOfTerms + ithTerm
print("Sum of 50 terms in the arithmetic sequence is:", sumOfTerms)
输出:
Common Difference in the arithmetic sequence is: 2
First term in the arithmetic sequence is: 3
Sum of 50 terms in the arithmetic sequence is: 2600
或者,我们也可以导出一个数学表达式来计算等差数列的 N 项之和。
我们知道 N 个数的和将等于 N *(所有项的平均值)。在这里,我们可以很容易地找到所有项的平均值。
对于第一项为 A₁ ,第 N 项为 A[N] 的等差数列,所有项的平均值定义为(A₁+A[N])/2。由于程序中会给出一个 ₁ 和公差带 D,我们可以求出A[N]= A₁+ (N-1)*D。
因此,算术序列中所有数字的平均值将变成 (2A₁+ (N-1)*D)/2。
随后,等差数列的 N 项之和将变为N*((2A₁+ (N-1)*D)/2)。
我们可以使用 python 中的这个公式来计算算术方程中 N 项的和,如下所示。
commonDifference = 2
print("Common Difference in the arithmetic sequence is:", commonDifference)
firstTerm = 3
print("First term in the arithmetic sequence is:", firstTerm)
# calculating sum of 50 terms
N = 50
sumOfTerms = (N * (2 * firstTerm + (N - 1) * commonDifference)) // 2
print("Sum of 50 terms in the arithmetic sequence is:", sumOfTerms)
输出:
Common Difference in the arithmetic sequence is: 2
First term in the arithmetic sequence is: 3
Sum of 50 terms in the arithmetic sequence is: 2600
结论
在这篇文章中,我们讨论了算术序列的基础和公式。我们还执行了不同的操作,比如在 python 中查找算术序列的第 N 项和 N 项之和。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。你可能也会喜欢这篇关于 python 中的复数的文章。
Python 中的 ASCII 值
原文:https://www.pythonforbeginners.com/basics/ascii-value-in-python
世界上有许多语言,因此有无数的符号。所有的符号都在计算机中用不同类型的编码表示,如 ASCII 和 Unicode。在本文中,我们将看到如何在 Python 中找到给定字符的 ASCII 值。
什么是 ASCII 值?
ASCII 代表“美国信息交换标准代码”。它仅包含 128 个字符,用于在计算机中表示不同的符号、十进制数字和英文字母。
在 ASCII 编码中,每个字符都被赋予一个 0 到 127 之间的数值。这个与字符相关的数值称为字符的 ASCII 值。
举个例子,
- “A”被赋予 ASCII 值 65。所有大写字母都按照各自的顺序被赋予了 65 之后的 ASCII 值。即“B”的 ASCII 值为 66,“C”的 ASCII 值为 67,依此类推。
- “a”被赋予了 ASCII 值 97。所有小写字母在 97 之后都被赋予了相应的 ASCII 值。即“b”的 ASCII 值为 98,“c”的 ASCII 值为 99,依此类推。
如何在 Python 中打印一个字符的 ASCII 值?
要打印给定字符的 ASCII 值,我们可以使用 python 中的 ord()函数。order()函数将给定的字符作为输入,并返回该字符的 ASCII 值。您可以在下面的示例中观察到这一点。
char1 = "A"
result1 = ord(char1)
print("ASCII value of the character {} is {}.".format(char1, result1))
char2 = "B"
result2 = ord(char2)
print("ASCII value of the character {} is {}.".format(char2, result2))
char3 = "C"
result3 = ord(char3)
print("ASCII value of the character {} is {}.".format(char3, result3))
char4 = "Z"
result4 = ord(char4)
print("ASCII value of the character {} is {}.".format(char4, result4))
char5 = "a"
result5 = ord(char5)
print("ASCII value of the character {} is {}.".format(char5, result5))
char6 = "b"
result6 = ord(char6)
print("ASCII value of the character {} is {}.".format(char6, result6))
char7 = "c"
result7 = ord(char7)
print("ASCII value of the character {} is {}.".format(char7, result7))
char8 = "z"
result8 = ord(char8)
print("ASCII value of the character {} is {}.".format(char8, result8))
输出:
ASCII value of the character A is 65.
ASCII value of the character B is 66.
ASCII value of the character C is 67.
ASCII value of the character Z is 90.
ASCII value of the character a is 97.
ASCII value of the character b is 98.
ASCII value of the character c is 99.
ASCII value of the character z is 122.
如果我们向ord()函数传递一个字符以外的值,它将引发一个 TypeError 异常。例如,如果我们传递一个包含多个字符而不是单个字符的字符串,ord()函数将引发如下的 TypeError。
char1 = "ABC"
result1 = ord(char1)
print("ASCII value of the character {} is {}.".format(char1, result1))
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
result1 = ord(char1)
TypeError: ord() expected a character, but string of length 3 found
类似地,如果我们将一个整数而不是一个字符传递给 ord()函数,它将引发 TypeError 异常,如下所示。
num1 = 123
result1 = ord(num1)
print("ASCII value of the character {} is {}.".format(num1, result1))
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
result1 = ord(num1)
TypeError: ord() expected string of length 1, but int found
结论
在本文中,我们讨论了 ASCII 编码。我们还看到了如何在 Python 中找到字符的 ASCII 值。要了解 python 中不同的值和允许的字符,可以阅读这些关于 python 中的 python 文字和数据类型的文章。
Python 中的 Assert 语句
原文:https://www.pythonforbeginners.com/basics/assert-statement-in-python
调试是软件开发人员旅程的重要部分之一。Python 编程语言还为调试程序提供了各种构造。一个这样的构造是 assert 语句。在本文中,我们将讨论什么是 assert 语句,它是如何工作的,以及我们如何在 python 中使用 assert 语句。
Python 中的 assert 语句是什么?
在 Python 中,Assert 语句是一个用于在程序中强制执行某些条件的构造。python 中 assert 语句的语法如下。
assert condition, message
- 这里断言是一个关键字。
- 条件包含需要为真的条件语句。
- 消息是当条件为假时将显示的语句。在断言语句中使用消息是可选的。
断言语句是如何工作的?
assert 语句通过使用 AssertionError 异常来工作。每当 assert 语句中给出的条件评估为真时,程序正常工作。
name = "Bill"
age = 20
assert age >= 0
print("{} is {} years old.".format(name,age))
输出:
Bill is 20 years old.
相反,如果 assert 语句中的条件评估为 False,则 AssertionError 异常发生,程序终止。
name = "Bill"
age = -20
assert age >= 0
print("{} is {} years old.".format(name,age))
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
assert age >= 0
AssertionError
如果我们在 assert 语句中传递一条消息,那么在 AssertionError 发生时也会打印这条消息。
name = "Bill"
age = -20
assert age >= 0, "Age cannot be negative."
print("{} is {} years old.".format(name,age))
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
assert age >= 0, "Age cannot be negative."
AssertionError: Age cannot be negative.
因此,我们可以说,当 assert 语句中的条件为真时,assert 语句什么也不做。如果 assert 语句中的条件为 False,python 解释器将使用适当的消息引发 AssertionError。
python 中如何使用 assert 语句?
不应该在 python 程序中使用 assert 语句来实现任何业务逻辑。assert 语句仅用于调试 python 程序。当程序没有产生预期的输出时,可以使用 assert 语句来检测错误发生的位置。
例如,假设您的程序因为像“年龄”这样的变量有负值而遇到错误,这不是我们想要的情况。
为了检测错误发生的位置,可以在使用“age”变量的每个语句之前放置一个 assert 语句。在每个 assert 语句中,您可以检查“age”的值是否大于零。您还可以添加一条消息来标识 IndexError 发生的位置,如下所示。
name = "Bill"
age = 10
assert age >= 0, "Age takes negative before first print statement."
print("{} is {} years old.".format(name, age))
name = "Sam"
age = -20
assert age >= 0, "Age takes negative before second print statement."
print("{} is {} years old.".format(name, age))
输出:
Bill is 10 years old.
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 7, in <module>
assert age >= 0, "Age takes negative before second print statement."
AssertionError: Age takes negative before second print statement.
在上面的例子中,程序提前终止。为了避免这种情况,可以使用 python try except 块。在这里,您可以在 try 块中编写代码,并处理由 except 块中的 assert 语句引发的 AssertionError,如下所示。
try:
name = "Bill"
age = 10
assert age >= 0, "Age takes negative before first print statement."
print("{} is {} years old.".format(name, age))
name = "Sam"
age = -20
assert age >= 0, "Age takes negative before second print statement."
print("{} is {} years old.".format(name, age))
except AssertionError as e:
print(e.args)
输出:
Bill is 10 years old.
('Age takes negative before second print statement.',)
结论
在本文中,我们讨论了 python 中的 assert 语句。我们还讨论了 assert 语句是如何工作的,以及如何在调试程序时使用它们。要了解更多关于错误的信息,您可以阅读这篇关于 python 中的异常的文章。
美丽的汤 4 蟒蛇
原文:https://www.pythonforbeginners.com/beautifulsoup/beautifulsoup-4-python
概观
本文是对 Python 中 BeautifulSoup 4 的介绍。如果你想了解更多,我推荐你阅读官方文档,在这里找到。
什么是美汤?
Beautiful Soup 是一个 Python 库,用于从 HTML 和 XML 文件中提取数据。
BeautifulSoup 3 还是 4?
美汤 3 已经被美汤 4 取代了。Beautiful Soup 3 只在 Python 2.x 上工作,但 Beautiful Soup 4 也在 Python 3.x 上工作,Beautiful Soup 4 速度更快,功能更多,可以与 lxml 和 html5lib 这样的第三方解析器一起工作。所有新项目都应该使用 Beautiful Soup 4。
安装美丽的汤
如果运行 Debian 或者 Ubuntu,可以用系统包管理器安装美汤
apt-get install python-bs4
美汤 4 是通过 PyPi 发布的,如果不能用系统打包器安装,可以用 easy_install 或者 pip 安装。这个包的名字是 beautifulsoup4,同样的包在 Python 2 和 Python 3 上工作。
easy_install beautifulsoup4
pip install beautifulsoup4
如果没有安装 easy_install 或者 pip,可以下载漂亮的 Soup 4 源码 tarball,用 setup.py 安装,python setup.py install
漂亮的一组用法
安装完成后,您可以开始使用 BeautifulSoup。在 Python 脚本的开始,导入库,现在你必须传递一些东西给 BeautifulSoup 来创建一个 Soup 对象。这可能是一个文档或一个 URL。BeautifulSoup 不会为你获取网页,你必须自己去做。这就是我结合使用 urllib2 和 BeautifulSoup 库的原因。
过滤
搜索 API 可以使用一些不同的过滤器。下面我将展示一些例子,告诉你如何将这些过滤器传递给 find_all 这样的方法。你可以根据标签的名称、属性、字符串的文本或者这些的组合来使用这些过滤器。
一根绳子
最简单的过滤器是字符串。将一个字符串传递给一个搜索方法,Beautiful Soup 将根据该字符串执行匹配。这段代码查找文档中所有的‘b’标签(你可以用任何你想查找的标签替换 b)
soup.find_all('b')
如果你传入一个字节串,Beautiful Soup 会假设这个字符串的编码是 UTF 8。您可以通过传入 Unicode 字符串来避免这种情况。
正则表达式
如果您传入一个正则表达式对象,Beautiful Soup 将使用 match()方法过滤该正则表达式。此代码查找名称以字母“b”开头的所有标签,在本例中是“body”标签和“b”标签:
import re
for tag in soup.find_all(re.compile("^b")):
print(tag.name)
此代码查找名称包含字母“t”的所有标签:
for tag in soup.find_all(re.compile("t")):
print(tag.name)
一份名单
如果您传入一个列表,Beautiful Soup 将允许对列表中的任何项目进行字符串匹配。这段代码查找所有的' a '标签和所有的' b '标签
print soup.find_all(["a", "b"])
真实的
值 True 匹配它所能匹配的一切。此代码查找文档中的所有标签,但不查找文本字符串:
for tag in soup.find_all(True):
print(tag.name)
一项功能
如果其他匹配都不适合您,请定义一个将元素作为唯一参数的函数。如果你想这么做,请查看官方文档。
漂亮的一组物体
例如,我们将使用您当前所在的网站(https://www.pythonforbeginners.com)来解析内容中的数据,我们只需为它创建一个 BeautifulSoup 对象,它将为我们传入的 url 内容创建一个 Soup 对象。从这一点来看,我们现在可以在 soup 对象上使用漂亮的 Soup 方法。我们可以使用 prettify 方法将 BS 解析树转换成格式良好的 Unicode 字符串
Find_all 方法
find_all 方法是 BeautifulSoup 中最常用的方法之一。它会查看标签的后代,并检索与您的过滤器匹配的所有后代。
soup.find_all("title")
soup.find_all("p", "title")
soup.find_all("a")
soup.find_all(id="link2")
让我们看一些如何使用 BS 4 的例子
from bs4 import BeautifulSoup
import urllib2
url = "https://www.pythonforbeginners.com"
content = urllib2.urlopen(url).read()
soup = BeautifulSoup(content)
print soup.prettify()
print title
>> 'title'? Python For Beginners
print soup.title.string
>> ? Python For Beginners
print soup.p
print soup.a
[Python For Beginners](https://www.pythonforbeginners.com)
导航解析树
如果您想知道如何浏览该树,请参见官方文档。在那里你可以读到以下内容:
往下走
- 使用标记名导航
- 。内容和。儿童
- 。后代
- 。字符串。字符串和剥离的 _ 字符串
上升
- 。父母
- 。双亲
横着走
- 。next_sibling 和。上一个 _ 兄弟姐妹
- 。下一个 _ 兄弟姐妹和。上一个 _ 兄弟姐妹
来来回回
- 。next_element 和。前一个元素
- 。next_elements 和。前 _ 个元素
提取在页面“a”标签中找到的所有 URL
一个常见的任务是使用 find_all 方法提取在页面的‘a’标签中找到的所有 URL,给我们一个带有标签‘a’的元素的完整列表。
for link in soup.find_all('a'):
print(link.get('href'))
Output:
..https://www.pythonforbeginners.com
..https://www.pythonforbeginners.com/python-overview-start-here/
..https://www.pythonforbeginners.com/dictionary/
..https://www.pythonforbeginners.com/python-functions-cheat-sheet/
..https://www.pythonforbeginners.com/lists/python-lists-cheat-sheet/
..https://www.pythonforbeginners.com/loops/
..https://www.pythonforbeginners.com/python-modules/
..https://www.pythonforbeginners.com/strings/
..https://www.pythonforbeginners.com/sitemap/
...
...
从页面中提取所有文本
另一个常见任务是从页面中提取所有文本:
print(soup.get_text())
Output:
Python For Beginners
Python Basics
Dictionary
Functions
Lists
Loops
Modules
Strings
Sitemap
...
...
从 Reddit 获取所有链接
作为最后一个例子,让我们从 Reddit 获取所有链接
from bs4 import BeautifulSoup
import urllib2
redditFile = urllib2.urlopen("http://www.reddit.com")
redditHtml = redditFile.read()
redditFile.close()
soup = BeautifulSoup(redditHtml)
redditAll = soup.find_all("a")
for links in soup.find_all('a'):
print (links.get('href'))
Output:
#content
..http://www.reddit.com/r/AdviceAnimals/
..http://www.reddit.com/r/announcements/
..http://www.reddit.com/r/AskReddit/
..http://www.reddit.com/r/atheism/
..http://www.reddit.com/r/aww/
..http://www.reddit.com/r/bestof/
..http://www.reddit.com/r/blog/
..http://www.reddit.com/r/funny/
..http://www.reddit.com/r/gaming/
..http://www.reddit.com/r/IAmA/
..http://www.reddit.com/r/movies/
..http://www.reddit.com/r/Music/
..http://www.reddit.com/r/pics/
..http://www.reddit.com/r/politics/
...
更多信息,请参见官方文档。
蟒蛇皮二叉查找树
原文:https://www.pythonforbeginners.com/data-structures/binary-search-tree-in-python
您可以在程序中使用不同的数据结构,如 python 字典、列表、元组或集合。但是这些数据结构不足以在程序中实现层次结构。在这篇文章中,我们将学习二叉查找树数据结构,并将在 python 中实现它们,以便更好地理解。
什么是二叉树?
二叉树是一种树形数据结构,其中每个节点最多可以有 2 个子节点。这意味着二叉树中的每个节点可以有一个、两个或没有子节点。二叉树中的每个节点都包含数据和对其子节点的引用。这两个孩子根据他们的位置被命名为左孩子和右孩子。二叉树中节点的结构如下图所示。

Node of a Binary Tree
我们可以用 python 实现一个二叉树节点,如下所示。
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild=None
什么是二叉查找树?
二叉查找树是一种二叉树数据结构,具有以下属性。
- 二叉查找树中没有重复的元素。
- 节点左边子节点的元素总是小于当前节点的元素。
- 节点的左子树包含比当前节点少的所有元素。
- 节点右边子节点的元素总是大于当前节点的元素。
- 节点右边的子树包含所有大于当前节点的元素。
以下是满足上述所有属性的二叉查找树的示例。

Binary search tree
现在,我们将在二叉查找树上实现一些基本操作。
如何在二叉查找树中插入元素?
我们将使用二分搜索法树的属性在其中插入元素。如果我们想在特定的节点插入一个元素,可能会出现三种情况。
- 当前节点可以是空节点,即无。在这种情况下,我们将使用要插入的元素创建一个新节点,并将这个新节点分配给当前节点。
- 要插入的元素可以大于当前节点处的元素。在这种情况下,我们将在当前节点的右子树中插入新元素,因为任何节点的右子树都包含比当前节点大的所有元素。
- 要插入的元素可以小于当前节点处的元素。在这种情况下,我们将在当前节点的左子树中插入新元素,因为任何节点的左子树都包含小于当前节点的所有元素。
为了插入元素,我们将从根节点开始,并根据上面定义的规则将元素插入到二叉查找树中。在二叉查找树中插入元素的算法在 Python 中实现如下。
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def insert(root, newValue):
# if binary search tree is empty, create a new node and declare it as root
if root is None:
root = BinaryTreeNode(newValue)
return root
# if newValue is less than value of data in root, add it to left subtree and proceed recursively
if newValue < root.data:
root.leftChild = insert(root.leftChild, newValue)
else:
# if newValue is greater than value of data in root, add it to right subtree and proceed recursively
root.rightChild = insert(root.rightChild, newValue)
return root
root = insert(None, 50)
insert(root, 20)
insert(root, 53)
insert(root, 11)
insert(root, 22)
insert(root, 52)
insert(root, 78)
node1 = root
node2 = node1.leftChild
node3 = node1.rightChild
node4 = node2.leftChild
node5 = node2.rightChild
node6 = node3.leftChild
node7 = node3.rightChild
print("Root Node is:")
print(node1.data)
print("left child of the node is:")
print(node1.leftChild.data)
print("right child of the node is:")
print(node1.rightChild.data)
print("Node is:")
print(node2.data)
print("left child of the node is:")
print(node2.leftChild.data)
print("right child of the node is:")
print(node2.rightChild.data)
print("Node is:")
print(node3.data)
print("left child of the node is:")
print(node3.leftChild.data)
print("right child of the node is:")
print(node3.rightChild.data)
print("Node is:")
print(node4.data)
print("left child of the node is:")
print(node4.leftChild)
print("right child of the node is:")
print(node4.rightChild)
print("Node is:")
print(node5.data)
print("left child of the node is:")
print(node5.leftChild)
print("right child of the node is:")
print(node5.rightChild)
print("Node is:")
print(node6.data)
print("left child of the node is:")
print(node6.leftChild)
print("right child of the node is:")
print(node6.rightChild)
print("Node is:")
print(node7.data)
print("left child of the node is:")
print(node7.leftChild)
print("right child of the node is:")
print(node7.rightChild)
输出:
Root Node is:
50
left child of the node is:
20
right child of the node is:
53
Node is:
20
left child of the node is:
11
right child of the node is:
22
Node is:
53
left child of the node is:
52
right child of the node is:
78
Node is:
11
left child of the node is:
None
right child of the node is:
None
Node is:
22
left child of the node is:
None
right child of the node is:
None
Node is:
52
left child of the node is:
None
right child of the node is:
None
Node is:
78
left child of the node is:
None
right child of the node is:
None
如何在二分搜索法树中搜索元素?
如您所知,二叉查找树不能有重复的元素,我们可以使用以下基于二分搜索法树属性的规则来搜索二叉查找树中的任何元素。我们将从根开始,并遵循这些属性
- 如果当前节点为空,我们将说该元素不在二叉查找树中。
- 如果当前节点中的元素大于要搜索的元素,我们将搜索其左子树中的元素,因为任何节点的左子树都包含小于当前节点的所有元素。
- 如果当前节点中的元素小于要搜索的元素,我们将搜索其右子树中的元素,因为任何节点的右子树都包含所有大于当前节点的元素。
- 如果当前节点的元素等于要搜索的元素,我们将返回 True。
基于上述属性在二叉查找树中搜索元素的算法在下面的程序中实现。
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def insert(root, newValue):
# if binary search tree is empty, create a new node and declare it as root
if root is None:
root = BinaryTreeNode(newValue)
return root
# if newValue is less than value of data in root, add it to left subtree and proceed recursively
if newValue < root.data:
root.leftChild = insert(root.leftChild, newValue)
else:
# if newValue is greater than value of data in root, add it to right subtree and proceed recursively
root.rightChild = insert(root.rightChild, newValue)
return root
def search(root, value):
# node is empty
if root is None:
return False
# if element is equal to the element to be searched
elif root.data == value:
return True
# element to be searched is less than the current node
elif root.data > value:
return search(root.leftChild, value)
# element to be searched is greater than the current node
else:
return search(root.rightChild, value)
root = insert(None, 50)
insert(root, 20)
insert(root, 53)
insert(root, 11)
insert(root, 22)
insert(root, 52)
insert(root, 78)
print("53 is present in the binary tree:", search(root, 53))
print("100 is present in the binary tree:", search(root, 100))
输出:
53 is present in the binary tree: True
100 is present in the binary tree: False
结论
在这篇文章中,我们讨论了二分搜索法树及其性质。我们还用 Python 实现了在二叉查找树中插入元素和在二叉查找树中搜索元素的算法。要了解更多关于 Python 中数据结构的知识,可以阅读这篇关于 python 中链表的文章。
Python 中二元元组到整数的转换
原文:https://www.pythonforbeginners.com/basics/binary-tuple-to-integer-in-python
二进制元组是只包含 0 和 1 作为元素的元组。在本文中,我们将讨论在 python 中将二进制元组转换为整数的不同方法。
如何在 Python 中将二进制元组转换成整数
考虑给我们以下二元元组。
myTuple= (1,1,0,1,1,0,1)
现在,我们必须从这个二元元组创建一个整数。整数将包含二进制表示中元组的所有数字。所以,数字会是(1101101)₂。在十进制表示中,(1101101)₂的值等于109。所以,我们的程序应该给出输出109。
为了将二进制数转换成十进制数,我们将数字的位数乘以 2 的幂。最右边的位乘以 2⁰。最右边第二个数字乘以 2¹,右边第三个数字乘以 2²。同样,第 N 位乘以 2^(N-1)。之后,将每个数字的值相加,得到十进制表示。
例如,我们可以将(1101101)₂ 转换为十进制表示如下。
(1101101)₂ = 1x2⁶+1x2⁵+0x2⁴+1x2³+1x2²+0x2¹+1x2⁰
=64+32+0+8+4+0+1
=109
为了在 python 中实现上述将二进制元组转换为整数的逻辑,我们将首先将变量myInt初始化为 0。我们还将使用 len()函数计算元组的长度。之后,我们将从右到左遍历元组,并使用 for 循环、 range()函数和元组长度将元素乘以 0 的幂。相乘后,我们将把这些值加到myInt中。在执行 for 循环后,我们将在myInt变量中得到整数输出。您可以在下面的示例中观察到这一点。
myTuple = (1, 1, 0, 1, 1, 0, 1)
myInt = 0
length = len(myTuple)
for i in range(length):
element = myTuple[length - i - 1]
myInt = myInt + element*pow(2, i)
print("The tuple is:", myTuple)
print("The output integer is:", myInt)
输出:
The tuple is: (1, 1, 0, 1, 1, 0, 1)
The output integer is: 109
使用字符串将二进制元组转换为整数
在 python 中,我们还可以使用字符串将二进制元组转换为整数。为此,我们将首先使用str()函数和map()函数将元组的所有元素转换为字符串。之后,我们将使用join()方法从元组的元素创建一个字符串。在字符串上调用 join()方法时,该方法将 iterable 对象作为输入,并返回由 iterable 元素组成的字符串。我们将首先创建一个空字符串,然后使用join() 方法从元组中获取字符串,如下所示。
myTuple = (1, 1, 0, 1, 1, 0, 1)
newTuple = map(str, myTuple)
myStr = "".join(newTuple)
print("The tuple is:", myTuple)
print("The output string is:", myStr)
输出:
The tuple is: (1, 1, 0, 1, 1, 0, 1)
The output string is: 1101101
获得字符串后,我们可以使用 int()函数直接将字符串转换为整数,如下所示。
myTuple = (1, 1, 0, 1, 1, 0, 1)
newTuple = map(str, myTuple)
myStr = "".join(newTuple)
myInt = int(myStr, 2)
print("The tuple is:", myTuple)
print("The output integer is:", myInt)
输出:
The tuple is: (1, 1, 0, 1, 1, 0, 1)
The output integer is: 109
在代码中,我们将值 2 作为第二个输入参数传递给了int()函数,以显示该字符串包含二进制数的位。
结论
在本文中,我们讨论了在 python 中将二进制元组转换为整数的两种方法。要了解更多关于字符串的知识,你可以阅读这篇关于 python 中的字符串连接的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
使用 Python 的 Bitly Shortener
原文:https://www.pythonforbeginners.com/code-snippets-source-code/bitly-shortener-with-python
开始之前
Bitly 允许用户缩短、分享和跟踪链接(URL)。
这是一种保存、分享和发现网络链接的方式。
Bitly 提供了公共 API,目的是让 python 程序员更容易使用。
第一步
第一步是前往dev.bitly.com,在那里你会找到 API
文档、最佳实践、代码库、公共数据集。
什么是 API 密钥?
互联网上的许多服务(如 Twitter、脸书..)要求你
有一个“API 密匙”。
应用编程接口密钥(API key)是由调用 API 的
计算机程序传入的代码,用于向网站标识调用程序、其开发者、
或其用户。
API 密钥用于跟踪和控制 API 的使用方式,例如
防止恶意使用或滥用 API。
API 密钥通常既作为唯一的标识符,又作为用于
认证的秘密令牌,并且通常具有一组对与之相关联的 API
的访问权限。
获取 Bitly API 密钥
为了能够让我们缩短链接(见下文),我们必须注册一个 API 键。
注册程序很容易解释,所以我不会在这篇文章中涉及。
在此创建您的 Bitly API 密钥
比特代码库
许多开发人员已经用几种不同的语言编写了代码库来与 bitly
API 交互。由于我们是用 Python 编程的,
我们当然对 Python 库感兴趣。
目前有三个不同的库可供选择,你可以在这里找到
在这篇文章中,我们将使用“ bitly-api-python 库,它也是
官方的 python 客户端。
Bitly API Python
bit.ly api 的安装非常简单
# Installation using PIP
pip install bitly_api
Downloading/unpacking bitly-api
Downloading bitly_api-0.2.tar.gz
Running setup.py egg_info for package bitly-api
Installing collected packages: bitly-api
Running setup.py install for bitly-api
Successfully installed bitly-api
Cleaning up...
缩短 URL
我们想写一个脚本,将减少 URL 长度,使分享
更容易。打开你最喜欢的文本编辑器,输入下面的代码。
将文件另存为 shortener.py
#!/usr/bin/env python
# Import the modules
import bitlyapi
import sys
# Define your API information
API_USER = "your_api_username"
API_KEY = "your_api_key"
b = bitlyapi.BitLy(API_USER, API_KEY)
# Define how to use the program
usage = """Usage: python shortener.py [url]
e.g python shortener.py http://www.google.com"""
if len(sys.argv) != 2:
print usage
sys.exit(0)
longurl = sys.argv[1]
response = b.shorten(longUrl=longurl)
print response['url']
Shortener.py 解释道
我们用#开始了这个计划!/usr/bin/env python
#!/usr/bin/env python
导入我们将在程序中使用的模块
import bitlyapi
import sys
定义我们的 API 信息
API_USER = "your_api_username"
API_KEY = "your_api_key"
b = bitlyapi.BitLy(API_USER, API_KEY)
定义如何使用程序
usage = """Usage: python shortener.py [url]
e.g python shortener.py http://www.google.com"""
if len(sys.argv) != 2:
print usage
sys.exit(0)
创建一个变量 longurl,并将值设置为传入的参数
longurl = sys.argv[1]
为 Bitly API 提供 longUrl response = b . shorten(longUrl = longUrl)
打印出 URL 值
print response['url']
Python 中的按位移位运算符
原文:https://www.pythonforbeginners.com/basics/bitwise-shift-operators-in-python
Python 中有各种类型的运算符,如算术运算符、比较运算符和位运算符。在我们的程序中,我们使用这些操作符来控制执行顺序和操作数据。在本文中,我们将研究不同的 python 按位移位操作符,它们的功能和例子。
什么是按位移位运算符?
按位移位运算符是二元运算符。这些运算符用于将一个数的二进制表示向左或向右移动一定的位置。按位移位运算符通常用于需要将整数乘以或除以 2 的幂的运算。这里,按位左移运算符用于将一个数乘以 2 的幂,而 python 中的按位右移运算符用于将一个数除以 2 的幂。
Python 中的按位右移运算符
python 中的按位右移运算符将输入数字的二进制表示形式的位向右移动指定的位数。移位产生的空位由 0 填充。
按位右移的语法是a>n。这里的“a”是其位将向右移动“n”位的数字。
从下图可以理解按位右移操作的工作原理。
假设我们必须将 14 的位移动 2 位。我们首先将它转换成二进制格式。
- 二进制格式的 14 写成 1110。
移位后,最右边的两位 1 和 0 将被丢弃,最左边的空位将被填充 0。14 >> 2 的输出将是二进制的 0011,它转换为整数格式的值 3。
在这里,您可以观察到我们已经将位移动了 2 位,因此输入数被 2²除,即 4。同样,如果我们将数字右移 n 位,数字的整数值将除以 2^n 。我们可以使用下面的程序在 python 中使用右移位操作符来验证这个输出。
myNum1 = 14
myNum2 = 2
shiftNum = myNum1 >> myNum2
print("Operand 1 is:", myNum1)
print("operand 2 is:", myNum2)
print("Result of the right shift operation on {} by {} bits is {}.".format(myNum1, myNum2, shiftNum))
输出:
Operand 1 is: 14
operand 2 is: 2
Result of the right shift operation on 14 by 2 bits is 3.
Python 中的按位左移运算符
Python 中的按位左移运算符将输入数字的二进制表示形式的位向左移动指定的位数。移位产生的空位由 0 填充。
按位左移的语法是a<n。这里的“a”是其位将向左移动“n”位的数字。
从下图可以理解按位左移操作的工作原理。
假设我们必须将 14 的位移动 2 位。我们首先将它转换成二进制格式。
- 二进制格式的 14 写成 1110。
移位后,最右边的空位将用 0 填充。14 << 2 的输出将是二进制的 111000,转换为整数格式的值 56。
在这里,您可以观察到,我们将位移动了 2 位,因此输入数乘以了 2²,即 4。同样,如果我们将该数左移 n 位,该数的整数值将乘以 2^n 。我们可以使用 python 中的左移位操作符,通过下面的程序来验证这个输出。
myNum1 = 14
myNum2 = 2
shiftNum = myNum1 << myNum2
print("Operand 1 is:", myNum1)
print("operand 2 is:", myNum2)
print("Result of the left shift operation on {} by {} bits is {}.".format(myNum1, myNum2, shiftNum))
输出:
Operand 1 is: 14
operand 2 is: 2
Result of the left shift operation on 14 by 2 bits is 56.
结论
在本文中,我们讨论了按位移位运算符、它们的语法以及 Python 中的例子。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
布尔值,Python 中的 True 或 False
什么是布尔?
布尔值是两个常量对象 False 和 True。
它们用于表示真值(其他值也可以被认为是
假或真)。
在数字上下文中(例如,当用作
算术运算符的参数时),它们的行为分别类似于整数 0 和 1。
内置函数 bool()可用于将任何值转换为布尔值,
如果该值可被解释为真值
它们分别被写成假的和真的。
布尔字符串
Python 中的字符串可以测试真值。
返回类型将是布尔值(真或假)
让我们举个例子,首先创建一个新变量并给它赋值。
my_string = "Hello World"
my_string.isalnum() #check if all char are numbers
my_string.isalpha() #check if all char in the string are alphabetic
my_string.isdigit() #test if string contains digits
my_string.istitle() #test if string contains title words
my_string.isupper() #test if string contains upper case
my_string.islower() #test if string contains lower case
my_string.isspace() #test if string contains spaces
my_string.endswith('d') #test if string endswith a d
my_string.startswith('H') #test if string startswith H
To see what the return value (True or False) will be, simply print it out.
my_string="Hello World"
print my_string.isalnum() #False
print my_string.isalpha() #False
print my_string.isdigit() #False
print my_string.istitle() #True
print my_string.isupper() #False
print my_string.islower() #False
print my_string.isspace() #False
print my_string.endswith('d') #True
print my_string.startswith('H') #True
布尔和逻辑运算符
布尔值响应逻辑运算符和/或
真假
假
真实与真实
真实
真假
假
假或真
真
假或假
假
记住,内置类型 Boolean 只能保存两个可能的
对象之一:True 或 False
Python 中的广度优先遍历
原文:https://www.pythonforbeginners.com/data-structures/breadth-first-traversal-in-python
图形是一种非线性数据结构。我们经常使用图形来表示不同的现实世界对象,如地图和网络。在本文中,我们将研究广度优先遍历来打印一个图中的所有顶点。我们还将在 Python 中实现广度优先遍历算法。
什么是广度优先遍历?
广度优先遍历是一种打印图中所有顶点的图遍历算法。在这个算法中,我们从一个顶点开始并打印它的值。然后我们打印当前顶点的所有邻居。之后,我们选择当前顶点的每个邻居,并打印其所有邻居。这个过程一直持续到图形中的所有顶点都被打印出来。
让我们通过在下图中执行广度优先遍历来理解这个过程。

Image of a Graph
假设我们从顶点 a 开始。
打印完顶点 A 后,我们将打印它的所有相邻顶点,即 B、D、E 和 f。
在打印 B、D、E 和 F 之后,我们将选择这些顶点中的一个。让我们选择 d。
由于 D 没有需要打印的邻居,我们将返回到 A 并选择 A 的另一个邻居。
由于 E 没有需要打印的邻居,我们将回到 A 并选择 A 的另一个邻居。
由于 F 没有需要打印的邻居,我们将回到 A 并选择 A 的另一个邻居。
现在,我们将打印 B 的所有尚未打印的邻居。因此,我们将打印 c。
此时,您可以观察到图中的所有顶点都已按 A、B、D、E、F、C 的顺序打印出来。因此,我们将终止该算法。
广度优先遍历算法
使用队列数据结构实现图的深度优先遍历算法。这里,我们假设我们有一个连通图。换句话说,我们可以从起始顶点到达图的每个顶点。
我们将维护一个队列来存储尚未打印的顶点,并维护一个列表来存储已访问的顶点。之后,我们将使用以下算法处理该图。
- 创建一个空队列 Q 来存储没有被打印的顶点。
- 创建一个空列表 L 来存储访问过的顶点。
- 将源顶点插入 Q 和 l。
- 如果 Q 为空,请转到 9。否则转到 5。
- 从 q 中取出一个顶点 v。
- 打印顶点 v。
- 将 v 的所有不在 L 中的邻居也插入到 Q 和 L 中。
- 转到第 4 节。
- 停下来。
可以使用上图中给出的图形的源代码来演示该算法。
from queue import Queue
graph = {'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
print("Given Graph is:")
print(graph)
def BFS_Algorithm(input_graph, source):
Q = Queue()
visited_vertices = list()
Q.put(source)
visited_vertices.append(source)
while not Q.empty():
vertex = Q.get()
print("At:",vertex)
print("Printing vertex:",vertex)
for u in input_graph[vertex]:
if u not in visited_vertices:
print("At vertex, adding {} to Q and visited_vertices".format(vertex, u))
Q.put(u)
visited_vertices.append(u)
print("visited vertices are: ", visited_vertices)
print("BFS traversal of graph with source A is:")
BFS_Algorithm(graph, "A")
输出:
Given Graph is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
BFS traversal of graph with source A is:
At: A
Printing vertex: A
At vertex, adding A to Q and visited_vertices
At vertex, adding A to Q and visited_vertices
At vertex, adding A to Q and visited_vertices
At vertex, adding A to Q and visited_vertices
visited vertices are: ['A', 'B', 'D', 'E', 'F']
At: B
Printing vertex: B
At vertex, adding B to Q and visited_vertices
visited vertices are: ['A', 'B', 'D', 'E', 'F', 'C']
At: D
Printing vertex: D
visited vertices are: ['A', 'B', 'D', 'E', 'F', 'C']
At: E
Printing vertex: E
visited vertices are: ['A', 'B', 'D', 'E', 'F', 'C']
At: F
Printing vertex: F
visited vertices are: ['A', 'B', 'D', 'E', 'F', 'C']
At: C
Printing vertex: C
visited vertices are: ['A', 'B', 'D', 'E', 'F', 'C']
在输出中,您可以观察到顶点是按照 A、B、D、E、F 和 c 的顺序打印的。
广度优先遍历在 Python 中的实现
我们已经讨论了图的广度优先遍历的一般思想,并观察了该算法如何使用 python 程序工作,我们可以如下实现广度优先遍历算法。
from queue import Queue
graph = {'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
print("Given Graph is:")
print(graph)
def BFS(input_graph, source):
Q = Queue()
visited_vertices = list()
Q.put(source)
visited_vertices.append(source)
while not Q.empty():
vertex = Q.get()
print(vertex, end= " ")
for u in input_graph[vertex]:
if u not in visited_vertices:
Q.put(u)
visited_vertices.append(u)
print("BFS traversal of graph with source A is:")
BFS(graph, "A")
输出:
Given Graph is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
BFS traversal of graph with source A is:
A B D E F C
结论
在本文中,我们讨论了 python 中全连通图的广度优先遍历算法。要了解更多关于其他算法的内容,可以阅读这篇关于 Python 中的有序树遍历的文章。
中断和继续语句
原文:https://www.pythonforbeginners.com/basics/break-and-continue-statements
Break 语句用于退出或“中断”一个 python for 循环或 while 条件循环。当循环结束时,代码从中断的循环开始执行下一行。
numbers = (1, 2, 3)
num_sum = 0
count = 0
for x in numbers:
num_sum = num_sum + x
count = count + 1
print(count)
if count == 2:
break
在本例中,循环将在计数等于 2 后中断。
continue 语句用于在循环的某些迭代中跳过循环中的代码。跳过代码后,循环从停止的地方继续。
for x in range(4):
if (x==2):
continue
print(x)
此示例将打印除 2 之外的从 0 到 4 的所有数字。
使用机械化在 Python 中浏览
原文:https://www.pythonforbeginners.com/python-on-the-web/browsing-in-python-with-mechanize
使用 Mechanize 浏览
Python 中的 mechanize 模块类似于 perl WWW:Mechanize。
它给你一个类似浏览器的对象来与网页交互。
这是一个如何在程序中使用它的例子。
import mechanize
br = mechanize.Browser()
br.open("http://www.example.com/")
跟随第二个链接,元素文本匹配正则表达式
response1 = br.follow_link(text_regex=r"cheeses*shop", nr=1)
assert br.viewing_html()
print br.title()
print response1.geturl()
print response1.info() # headers
print response1.read() # body
要从网站获取响应代码,您可以
from mechanize import Browser
browser = Browser()
response = browser.open('http://www.google.com')
print response.code
从网站获取所有表单
import mechanize
br = mechanize.Browser()
br.open("http://www.google.com/")
for f in br.forms():
print f
我在http://stockrt.github.com发现这个帖子,非常准确地描述了
如何使用 mechanize 在 Python 中模拟一个浏览器。
用 Python 浏览(由 Drew Stephens 编写)
#!/usr/bin/python
import re
from mechanize import Browser
br = Browser()
忽略 robots.txt
br.set_handle_robots( False )
谷歌需要一个不是机器人的用户代理
br.addheaders = [('User-agent', 'Firefox')]
检索 Google 主页,保存响应
br.open( "http://google.com" )
选择搜索框并搜索“foo”
br.select_form( 'f' )
br.form[ 'q' ] = 'foo'
获取搜索结果
br.submit()
找到 foofighters.com 的链接;我们为什么要搜索?
resp = None
for link in br.links():
siteMatch = re.compile( 'www.foofighters.com' ).search( link.url )
if siteMatch:
resp = br.follow_link( link )
break
打印网站
content = resp.get_data()
print content
上面的脚本被分割开来,以便于阅读
Python 中的 Bytearray
原文:https://www.pythonforbeginners.com/data-types/bytearray-in-python
你一定学过 python 中不同的数据类型,比如字符串和数字数据类型,比如整数和浮点数。在本文中,您将了解 python 编程语言中另一种称为 bytearray 的数据类型。您将学习 python 中 bytearray 背后的基本概念,并对 bytearray 对象实现不同类型的操作来理解这些概念。
Python 中的 bytearray 是什么?
python 中的 bytearray 是一个字节数组,可以保存机器可读格式的数据。当任何数据被保存在辅助存储器中时,它根据特定类型的编码被编码,例如对于字符串是 ASCII、UTF-8 和 UTF-16,对于图像是 PNG、JPG 和 JPEG,对于音频文件是 mp3 和 wav,并且被转换成字节对象。当我们使用 python read file 操作再次访问数据时,它被解码成相应的文本、图像或音频。因此,byte 对象包含机器可读的数据,bytearray 对象是字节数组。
如何在 Python 中创建 bytearray 对象?
我们可以使用 bytearray()方法在 python 中创建一个 bytearray 对象。bytearray()函数将三个参数作为输入,它们都是可选的。必须转换为 bytearray 的对象作为第一个参数传递。仅当第一个参数是字符串时,才使用第二个和第三个参数。在这种情况下,第二个参数是字符串的编码格式,第三个参数是编码失败时执行的错误响应的名称。函数的作用是:返回一个 bytearray 对象。在接下来的小节中,我们将通过从不同的数据对象创建 bytes 对象来理解 bytearray()函数的工作原理。
创建 bytearray 对象
要创建给定大小的 bytearray 对象,我们可以将所需的 bytearray 大小作为 bytearray()函数的输入。成功执行后,它返回给定大小的 bytearray 对象,初始化为零,如下所示。
myObj=bytearray(10)
print("The bytearray object is:",myObj)
print("Length of the bytearray object is:",len(myObj))
输出:
The bytearray object is: bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
Length of the bytearray object is: 10
为了将字符串转换为 bytearray 对象,我们将字符串作为第一个输入,将编码类型作为第二个输入参数传递给 bytearray()函数。然后,它返回字符串的 bytearray,如下所示。
myString="pythonforbeginners.com"
print("The string is:",myString)
myObj=bytearray(myString,"UTF-8")
print("The bytearray object is:",myObj)
输出:
The string is: pythonforbeginners.com
The bytearray object is: bytearray(b'pythonforbeginners.com')
我们可以使用 python 中的 bytearray()函数将整数列表转换为 bytearray。bytearray()函数将 0 到 255 之间的整数列表作为输入,并返回相应的 bytearray 对象,如下所示。
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
输出:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
对于不在 0 到 255 之间的整数值,bytearray 函数按如下方式引发 ValueError。
myList=[1,2,56,78,900]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/main.py", line 3, in <module>
myObj=bytearray(myList)
ValueError: byte must be in range(0, 256)
The List is: [1, 2, 56, 78, 900]
我们可以如下使用 python try-except 处理上述异常。
myList=[1,2,56,78,900]
print("The List is:",myList)
try:
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
except Exception as e:
print(str(e))
输出:
The List is: [1, 2, 56, 78, 900]
byte must be in range(0, 256)
对 bytearray 对象的操作
虽然 byte 对象是不可变的,但是 bytearray 对象是可变的,可以被修改,它们的行为几乎和 python 列表一样。以下是对 bytearray 对象的一些常见操作。
Bytearray 支持索引和切片。我们可以使用索引来获取特定索引处的数据,或者我们可以对 bytearray 进行切片来获取两个索引之间的数据,如下所示。
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
sliced_obj=myObj[0:2]
indexed_obj=myObj[1]
print("Sliced part of bytearray is:",sliced_obj)
print("Data at index 1 of bytearray is:",indexed_obj)
输出:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
Sliced part of bytearray is: bytearray(b'\x01\x02')
Data at index 1 of bytearray is: 2
由于 bytearray 对象是可变的,我们也可以使用索引和切片来修改 bytearray 对象,如下所示。
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj[0:2]=[15,16]
myObj[4]=34
print("The modified bytearray object is:",myObj)
输出:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x0f\x108N"')
我们还可以使用 insert()方法将数据插入 bytearray 对象的给定索引处,如下所示。
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj.insert(1,23)
print("The modified bytearray object is:",myObj)
输出:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x01\x17\x028NZ')
我们可以使用 append()方法将数据追加到 bytearray 对象中,如下所示。
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
myObj.append(105)
print("The modified bytearray object is:",myObj)
输出:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x01\x028NZi')
我们还可以使用 del 语句删除特定索引处或两个索引之间的数据,如下所示。
myList=[1,2,56,78,90]
print("The List is:",myList)
myObj=bytearray(myList)
print("The bytearray object is:",myObj)
del myObj[0]
del myObj[1:3]
print("The modified bytearray object is:",myObj)
输出:
The List is: [1, 2, 56, 78, 90]
The bytearray object is: bytearray(b'\x01\x028NZ')
The modified bytearray object is: bytearray(b'\x02Z')
结论
在本文中,我们研究了 python 中的 bytearray 数据结构。我们还将不同的数据类型转换为 bytearray,并使用内置函数执行了诸如将数据追加到 bytearray、插入数据和从 bytearray 中删除数据之类的操作。请继续关注更多内容丰富的文章。
Python 中的字节
原文:https://www.pythonforbeginners.com/basics/bytes-in-python
你一定学过 python 中不同的数据类型,比如字符串和数字数据类型,比如整数和浮点数。在本文中,您将了解另一种称为字节的数据类型。您将学习 python 中字节背后的基本概念,并对字节实现不同类型的操作来理解这些概念。
Python 中的字节是什么?
通常,当我们在辅助存储器中保存任何数据时,它都根据某种类型的编码进行编码,例如字符串的 ASCII、UTF-8 和 UTF-16,图像的 PNG、JPG 和 JPEG,以及音频文件的 mp3 和 wav,并被转换成字节对象。当我们使用 python 读文件操作再次访问数据时,它被解码成相应的文本、图像或音频。字节对象包含机器可读的数据,我们可以将字节对象直接存储到二级存储器中。
在 python 中,我们可以从列表、字符串等其他数据中显式地创建字节对象。
如何在 Python 中创建字节?
要创建字节对象,我们可以使用 bytes()函数。bytes()函数将三个参数作为输入,它们都是可选的。必须转换成字节的对象作为第一个参数传递。仅当第一个参数是字符串时,才使用第二个和第三个参数。在这种情况下,第二个参数是字符串的编码,第三个参数是编码失败时执行的错误响应的名称。bytes()函数返回一个不可变的字节对象。在接下来的小节中,我们将通过从不同的数据对象创建 bytes 对象来理解 bytes()函数的工作原理。
创建一个给定大小的字节对象
要创建任意给定大小的 bytes 对象,我们将把大小作为输入传递给 bytes()方法,然后创建一个所需大小的 bytes 对象,它被初始化为全零。这可以从下面的例子中理解。
bytes_obj = bytes(10)
print("The bytes object is:", bytes_obj)
print("Size of the bytes object is:", len(bytes_obj) )
输出:
The bytes object is: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Size of the bytes object is: 10
将字符串转换为字节
要将字符串转换为 bytes 对象,我们将把字符串作为第一个输入,把编码作为第二个输入传递给 bytes()函数。错误响应还有第三个参数,但为了简单起见,此时可以忽略。该函数返回一个包含编码字符串的 bytes 对象。这可以这样理解。
myString = "Pythonforbeginners.com"
print("The given string is:" , myString)
bytes_obj = bytes(myString , "UTF-8")
print("The bytes object is:", bytes_obj)
print("Size of the bytes object is:", len(bytes_obj) )
输出:
The given string is: Pythonforbeginners.com
The bytes object is: b'Pythonforbeginners.com'
Size of the bytes object is: 22
将列表转换为字节
我们还可以使用 bytes()函数将任何可迭代对象(如 list 或 tuple)转换为 bytes 对象。要执行这个操作,我们只需将 iterable 对象传递给 bytes()函数,该函数返回相应的 bytes 对象。请记住,字节对象是不可变的,不能被修改。我们可以使用 bytes()函数将列表转换成字节,如下所示。
myList = [1,2,3,4,5]
print("The given list is:" , myList)
bytes_obj = bytes(myList)
print("The bytes object is:", bytes_obj)
print("Size of the bytes object is:", len(bytes_obj) )
输出:
The given list is: [1, 2, 3, 4, 5]
The bytes object is: b'\x01\x02\x03\x04\x05'
Size of the bytes object is: 5
记住传递给 bytes()函数的列表应该只包含元素。用浮点数或字符串传递 s list 会导致 bytes()函数抛出 TypeError。
结论
在本文中,我们已经了解了什么是 bytes 对象,以及如何使用 bytes()方法从 iterables 和 strings 创建 bytes 对象。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
用 Python 计算平均值
原文:https://www.pythonforbeginners.com/basics/calculate-average-in-python
我们必须在 python 程序中执行许多数学计算来处理任何数据。在这篇文章中,我们将看看在 python 中计算给定数字平均值的不同方法。
如何计算给定数字的平均值
给定数字的平均值定义为所有数字的总和除以这些数字的总数。
例如,如果给定数字 1、2、4、5、6、7、8、10 和 12,我们可以通过首先计算它们的总和,然后用这些总和除以数字的总数来计算这些数字的平均值。这里,所有给定数字的和是 55,它们的总数是 9。因此,所有数字的平均值将是 55/9,即 6.111。
在 Python 中使用 for 循环计算平均值
如果给我们一个数字列表,我们可以使用 for 循环计算平均值。首先,我们将声明一个 sumofNums 和一个 count 变量,并将它们初始化为 0。然后,我们将遍历列表中的每个元素。在遍历时,我们将把每个元素添加到 sumofNums 变量中。同时,我们还会将计数变量加 1。遍历整个列表后,我们将在 sumofNums 变量中得到列表中所有元素的总和,并在 count 变量中得到元素的总数。现在,我们可以将 sumofNums 除以 count 来获得列表元素的平均值,如下所示。
numbers = [1, 2, 34, 56, 7, 23, 23, 12, 1, 2, 3, 34, 56]
sumOfNums = 0
count = 0
for number in numbers:
sumOfNums += number
count += 1
average = sumOfNums / count
print("The list of numbers is:", numbers)
print("The average of all the numbers is:", average)
输出:
The list of numbers is: [1, 2, 34, 56, 7, 23, 23, 12, 1, 2, 3, 34, 56]
The average of all the numbers is: 19.53846153846154
使用内置函数计算平均值
不使用 for 循环,我们可以使用 python 中的内置函数来计算给定列表中元素的平均值。
我们可以使用 sum()方法计算列表中所有元素的总和,然后使用 len()方法计算列表中元素的总数。这样,我们将得到这些数字的总和以及这些数字的总数,我们可以用它们来计算平均值,如下所示。
numbers = [1, 2, 34, 56, 7, 23, 23, 12, 1, 2, 3, 34, 56]
sumOfNums = sum(numbers)
count = len(numbers)
average = sumOfNums / count
print("The list of numbers is:", numbers)
print("The average of all the numbers is:", average)
输出:
The list of numbers is: [1, 2, 34, 56, 7, 23, 23, 12, 1, 2, 3, 34, 56]
The average of all the numbers is: 19.53846153846154
或者,我们可以使用统计模块的 mean()方法直接计算列表元素的平均值。我们将给定的数字列表作为输入传递给 mean()方法,它将返回数字的平均值,如下例所示。
import statistics
numbers = [1, 2, 34, 56, 7, 23, 23, 12, 1, 2, 3, 34, 56]
average = statistics.mean(numbers)
print("The list of numbers is:", numbers)
print("The average of all the numbers is:", average)
输出:
The list of numbers is: [1, 2, 34, 56, 7, 23, 23, 12, 1, 2, 3, 34, 56]
The average of all the numbers is: 19.53846153846154
结论
在本文中,我们讨论了在 Python 中计算给定数字平均值的不同方法。你可以在关于 python 操作符的文章中读到其他操作。
Python 日历:显示日历
原文:https://www.pythonforbeginners.com/code-snippets-source-code/calendar-show-calendars
这个脚本将要求输入一年。然后,它将接受该输入并返回整年的日历。
import calendar
print "Show a given years monthly calendar"
print ''
year = int(raw_input("Enter the year"))
print ''
calendar.prcal(year)
print ''
在脚本中添加一个 while 循环,再尝试一年。
import calendar
while True:
print "Show a given years monthly calendar"
print ''
year = int(raw_input("Enter the year"))
print ''
calendar.prcal(year)
print ''
raw_input("Press enter to go on ...")
有关日历模块的更多信息,请参见官方文档。
Python 中的可调用对象
原文:https://www.pythonforbeginners.com/basics/callable-objects-in-python
你可能听说过 python 中的函数是可调用对象。在本文中,我们将讨论术语“可调用对象”的确切含义。我们将讨论可调用对象实现背后的概念,并将实现程序来演示 python 中可调用对象的使用。
调用对象是什么意思?
我们通过在任何对象后面加上圆括号来称呼它们。例如,当我们必须调用一个函数时,我们在它们后面放上圆括号,如下所示。
def add(num1, num2):
value = num1 + num2
return value
val = add(10, 20)
print("The sum of {} and {} is {}".format(10, 20, val))
输出:
The sum of 10 and 20 is 30
这里,我们调用了 add()函数,将 10 和 20 作为输入参数。该函数在执行后返回输入数字的总和。
同理,我们也可以调用其他可调用对象。但是,如果我们调用一个不可调用的对象,python 解释器将抛出一个 TypeError 异常,并给出一条消息,说明该对象不可调用。这可以通过以下方式观察到。
val = 10
val()
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 2, in <module>
val()
TypeError: 'int' object is not callable
在这里,你可以看到我们已经定义了一个整型变量,然后我们调用了它。在执行时,它会引发 TypeError 异常,并显示一条消息,说明“int”对象不可调用。
调用一个函数可以,但是调用一个整型变量会引发异常,这是什么原因?让我们找出答案。
Python 中什么是可调用对象?
python 中的可调用对象是这样一种对象,它在被调用时执行一些代码,而不是引发 TypeError。
每个可调用对象都在其类定义中实现了 call()方法。如果我们使用这个细节来定义可调用对象,那么 python 中的可调用对象就是那些在类定义中实现了 call()方法的对象。
如果对象在其类定义中没有 call()方法的实现,则每当调用该对象时,它都会引发 TypeError 异常。这可以从下面的例子中看出。
class Website:
def __init__(self):
self.name = "Python For Beginners"
myWebsite = Website()
myWebsite()
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 7, in <module>
myWebsite()
TypeError: 'Website' object is not callable
这里,对象 myWebsite 在其类 Website 的定义中没有 call()方法的实现。因此,它会引发 TypeError 异常,并显示一条消息,说明在调用“Website”对象时,它是不可调用的。
现在让我们在打印网站地址的网站类中实现 call()方法。观察这里的输出。
class Website:
def __init__(self):
self.name = "Python For Beginners"
def __call__(self, *args, **kwargs):
print("Called me?")
print("I am available at pythonforbeginners.com")
myWebsite = Website()
myWebsite()
输出:
Called me?
I am available at pythonforbeginners.com
现在,您可能很清楚,我们可以调用任何在其类定义中实现了 call()方法的对象。
如何在 python 中创建可调用对象?
我们在上面已经看到,所有可调用对象在它们的类定义中都有 call()方法的实现。因此,要在 python 中创建一个可调用的对象,我们将在对象的函数定义中实现 call()方法,如 abve 给出的示例所示。
class Website:
def __init__(self):
self.name = "Python For Beginners"
def __call__(self, *args, **kwargs):
print("Called me?")
print("I am available at pythonforbeginners.com")
myWebsite = Website()
myWebsite()
输出:
Called me?
I am available at pythonforbeginners.com
结论
在本文中,我们讨论了 python 中的可调用对象。我们还讨论了如何使用 call()方法创建可调用对象。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
数据框架中的列名大写
原文:https://www.pythonforbeginners.com/basics/capitalize-column-names-in-a-dataframe
Pandas 数据帧用于在 python 中处理表格数据。在本文中,我们将讨论在 python 中大写数据帧中的列名的不同方法。
使用 str.upper()方法将列名大写
数据帧的列名存储在'columns'属性中。我们可以使用 columns 属性检索所有的列名,如下所示。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
columns = df1.columns
print("The column names are:")
for name in columns:
print(name)
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
The column names are:
Name
Roll Number
Subject
由于列名存储在一个列表中,我们可以分配一个包含原始列名的大写值的新列表来大写数据帧的列名。为此,我们将首先创建一个空列表,比如myList。之后,我们将使用upper()方法将每个列名转换成大写。
在字符串上调用upper()方法时,会返回一个包含大写字符的新字符串。我们将为每个列名获取一个大写字符串,并将其存储在myList中。之后,我们将把myList分配给columns属性。这样,大写字符串将作为列名分配给数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
columns = df1.columns
print("Originally, the column names are:")
for name in columns:
print(name)
myList = []
for name in columns:
myList.append(name.upper())
df1.columns = myList
columns = df1.columns
print("After capitalization, the column names are:")
for name in columns:
print(name)
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
Originally, the column names are:
Name
Roll Number
Subject
After capitalization, the column names are:
NAME
ROLL NUMBER
SUBJECT
在上面的例子中,不使用 for 循环,您可以使用 list comprehension 来大写列名,如下所示。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
columns = df1.columns
print("Originally, the column names are:")
for name in columns:
print(name)
df1.columns = [x.upper() for x in columns]
columns = df1.columns
print("After capitalization, the column names are:")
for name in columns:
print(name)
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
Originally, the column names are:
Name
Roll Number
Subject
After capitalization, the column names are:
NAME
ROLL NUMBER
SUBJECT
使用 series.str.upper()方法将列名大写
不使用为字符串定义的upper()方法,我们可以使用Series.str.upper() 方法来大写数据帧中的列名。为了大写列名,我们可以简单地调用存储列名的索引对象上的upper()方法。当在dataframe.columns对象上调用Series.str.upper()时,返回另一个对象,其中所有的列名都是大写的。我们可以将由 upper()方法返回的对象分配给 dataframe 的columns属性,以大写列名,如下例所示。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
columns = df1.columns
print("Originally, the column names are:")
for name in columns:
print(name)
df1.columns = df1.columns.str.upper()
print("After capitalization, the column names are:")
columns = df1.columns
for name in columns:
print(name)
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
Originally, the column names are:
Name
Roll Number
Subject
After capitalization, the column names are:
NAME
ROLL NUMBER
SUBJECT
使用 rename()方法将列名大写
我们还可以使用rename() 方法来大写数据帧中的列名。为此,我们可以将upper()方法作为输入参数传递给rename() 方法中的columns参数。执行后,rename()方法返回一个带有大写列名的 dataframe。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
columns = df1.columns
print("Originally, the column names are:")
for name in columns:
print(name)
newDf = df1.rename(columns=str.upper)
print("After capitalization, the column names are:")
columns = newDf.columns
for name in columns:
print(name)
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
Originally, the column names are:
Name
Roll Number
Subject
After capitalization, the column names are:
NAME
ROLL NUMBER
SUBJECT
在这种方法中,不修改原始数据帧。取而代之的是,用大写的列名创建一个新的 dataframe。要修改原始数据帧中的列名,可以使用inplace参数,并在rename()方法中给它赋值True。这样,原始数据帧将被修改。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
columns = df1.columns
print("Originally, the column names are:")
for name in columns:
print(name)
df1.rename(columns=str.upper, inplace=True)
print("After capitalization, the column names are:")
columns = df1.columns
for name in columns:
print(name)
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
Originally, the column names are:
Name
Roll Number
Subject
After capitalization, the column names are:
NAME
ROLL NUMBER
SUBJECT
结论
在本文中,我们讨论了在 python 中大写数据帧中的列名的不同方法。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中字典理解的文章。您可能也会喜欢这篇关于 python 中的字符串连接的文章。
检查 Python 中不相交的集合
原文:https://www.pythonforbeginners.com/basics/check-for-disjoint-sets-in-python
在 python 中,集合是用于存储唯一不可变对象的容器对象。在本文中,我们将讨论 python 中的不相交集合。我们还将讨论 python 中检查不相交集合的不同方法。
什么是不相交集合?
如果两个集合没有任何公共元素,则称它们是不相交的。如果两个给定的集合之间存在任何公共元素,那么它们就不是不相交的集合。
假设我们已经设置了 A、B 和 C,如下所示。
A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8, 10, 12}
C = {10, 20, 30, 40, 50}
在这里,您可以观察到集合 A 和集合 B 有一些共同的元素,即 2、4、6 和 8。因此,它们不是不相交的集合。另一方面,集合 A 和集合 C 没有公共元素。因此,集合 A 和集合 C 将被称为不相交集合。
Python 中如何检查不相交集合?
要检查不相交的集合,我们只需检查给定集合中是否存在任何公共元素。如果两个集合中有公共元素,那么这两个集合就不是不相交的集合。否则,它们将被视为不相交的集合。
为了实现这个逻辑,我们将声明一个变量isDisjoint并将其初始化为True,假设两个集合都是不相交的集合。之后,我们将使用 for 循环遍历其中一个输入集。在遍历时,我们将检查集合中的每个元素是否存在于另一个集合中。如果我们在第一个集合中找到任何属于第二个集合的元素,我们将把值False赋给变量isDisjoint,表示这些集合不是不相交的集合。
如果输入集之间没有公共元素,那么在执行 for 循环后,isDisjoint变量将保持为True。因此,表示这些集合是不相交的集合。
def checkDisjoint(set1, set2):
isDisjoint = True
for element in set1:
if element in set2:
isDisjoint = False
break
return isDisjoint
A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8, 10, 12}
C = {10, 20, 30, 40, 50}
print("Set {} is: {}".format("A", A))
print("Set {} is: {}".format("B", B))
print("Set {} is: {}".format("C", C))
print("Set A and B are disjoint:", checkDisjoint(A, B))
print("Set A and C are disjoint:", checkDisjoint(A, C))
print("Set B and C are disjoint:", checkDisjoint(B, C))
输出:
Set A is: {1, 2, 3, 4, 5, 6, 7, 8}
Set B is: {2, 4, 6, 8, 10, 12}
Set C is: {40, 10, 50, 20, 30}
Set A and B are disjoint: False
Set A and C are disjoint: True
Set B and C are disjoint: False
建议阅读:Python 中的聊天应用
使用 isdisjoint()方法检查不相交的集合
除了上面讨论的方法,我们可以使用isdisjoint()方法来检查 python 中不相交的集合。当在一个集合上调用时,isdisjoint() 方法将另一个集合作为输入参数。执行后,如果集合是不相交的集合,则返回True。否则返回False。您可以在下面的示例中观察到这一点。
A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8, 10, 12}
C = {10, 20, 30, 40, 50}
print("Set {} is: {}".format("A", A))
print("Set {} is: {}".format("B", B))
print("Set {} is: {}".format("C", C))
print("Set A and B are disjoint:", A.isdisjoint(B))
print("Set A and C are disjoint:", A.isdisjoint(C))
print("Set B and C are disjoint:", B.isdisjoint(C))
输出:
Set A is: {1, 2, 3, 4, 5, 6, 7, 8}
Set B is: {2, 4, 6, 8, 10, 12}
Set C is: {40, 10, 50, 20, 30}
Set A and B are disjoint: False
Set A and C are disjoint: True
Set B and C are disjoint: False
结论
在本文中,我们讨论了在 python 中检查不相交集合的两种方法。要了解更多关于集合的知识,你可以阅读这篇关于 python 中集合理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
检查 Python 中的 Harshad 数
原文:https://www.pythonforbeginners.com/basics/check-for-harshad-number-in-python
数字有很多特殊性。根据专业,他们被赋予独特的名字。一个这样的特殊号码是哈沙德号码或尼文号码。在本文中,我们将讨论一个程序来检查一个给定的数是否是一个 Harshad 数。
什么是 Harshad 数?
如果一个数能被它的数位之和整除,那么这个数就是哈沙德数或尼文数。换句话说,如果给我们一个能被它自己的数字之和整除的数,这个数就叫做 Harshad 数。
例如,让我们考虑 4320 这个数字。它的数字之和是 9,可以通过将数字 4、3、2 和 0 相加得到。我们可以看到 4320 能被 9 整除。因此,4320 是一个苛刻的数字。另一方面,4321 中的位数之和是 10。在这里,4321 不能被 10 整除。因此,这不是一个苛刻的数字。
在 Python 中检查 Harshad 数的程序
为了检查一个数是否是 Harshad 数,我们将首先计算给定数的位数之和。之后,我们将数字除以位数之和,看它是否能被完全整除。如果这个数能被数位之和整除,我们就说它是一个 Harshad 数。否则不会。
为了编写完整的程序,我们将首先编写一个函数来计算给定数字的位数之和。为此,我们将继续用 10 除这个数,直到这个数变成 0。每次我们将数字除以 10,我们得到最右边的数字作为余数。我们可以用这个余数,通过把所有的余数相加,直到数字变成 0,来求数字的和。
python 中用于计算数字位数总和的以下函数接受一个数字,并返回该数字的位数总和。
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
input_number = 4320
output = calculate_sum_of_digits(input_number)
print("Sum of digits of {} is {}.".format(input_number, output))
输出:
Sum of digits of 4320 is 9.
求完位数和后,我们将数除以位数和。如果除法的余数是零,我们就说这个数是哈沙德数或尼文数。否则,我们将打印出该号码不是 Harshad 号码。
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
def check_for_harshad_number(N):
sumOfDigits = calculate_sum_of_digits(N)
if N % sumOfDigits == 0:
return True
else:
return False
input_number = 4320
output = check_for_harshad_number(input_number)
print("{} is a Harshad Number:{}".format(input_number, output))
input_number = 4321
output = check_for_harshad_number(input_number)
print("{} is a Harshad Number:{}".format(input_number, output))
输出:
4320 is a Harshad Number:True
4321 is a Harshad Number:False
结论
在本文中,我们讨论了什么是哈沙德数或尼文数。我们还用 python 实现了一个程序来检查一个给定的数是否是 Harshad 数。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。你可能也会喜欢这篇关于 python 中的复数的文章。
在 Python 中检查 Moran 数
原文:https://www.pythonforbeginners.com/basics/check-for-moran-number-in-python
数字有魔力。人们根据他们的专业给不同的数字命名。在本文中,我们将讨论什么是莫兰数。我们还将用 python 实现一个程序来检查一个数是否是 Moran 数。
什么是莫兰数?
莫兰数是这样一个数,当它除以它的数字之和时,结果是一个质数。换句话说,如果我们取一个莫兰数,计算它的位数之和,用这个数除以位数之和,结果将是一个质数。莫兰数是哈沙德数的子集。
例如,42 是一个莫兰数。如果计算它的位数之和,就是 6。42 除以 6 的结果是 7,这是一个质数。因此,42 是一个莫兰数。
另一方面,如果我们取 20,它的位数之和是 2。20 除以 2 的结果是 10,这不是质数。因此,20 不是一个莫兰数。
在 Python 中检查 Moran 数
要在 Python 中检查 Moran 数,我们必须执行以下操作。
- 计算给定数字的位数之和。
- 用数字的和除这个数。
- 检查除法的结果是否是质数。
让我们先讨论如何求数的位数之和。
要计算给定数字的位数之和,我们将该数字除以 10,直到该数字变为 0。在每次除法运算中,我们将得到最右边的数字作为余数。我们将使用余数来计算数字的总和,方法是将每个除法运算中的余数相加,如下所示。
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
求出位数之和后,就可以用给定的数除以位数之和来求结果。现在,我们必须检查这个数是否是质数。为此,我们将结果除以从 2 到结果平方根的所有数字。如果结果能被这个范围内的任何一个数整除,这个数就不是质数。下面给出的 isPrime()函数执行这个操作。它接受一个数字作为输入参数,如果给定的数字是质数,则返回 True。否则,它返回 False。
def isPrime(N):
count = 2
while count ** 2 <= N:
if N % count == 0:
return False
count = count + 1
return True
Python 中检查 Moran 数的程序
在定义了计算数字总和和检查素数的函数之后,我们可以用 Python 编写一个程序来检查 Moran 数,如下所示。
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
def isPrime(N):
count = 2
while count ** 2 <= N:
if N % count == 0:
return False
count = count + 1
return True
def check_for_moran_number(N):
sumOfDigits = calculate_sum_of_digits(N)
if N % sumOfDigits == 0:
result = N // sumOfDigits
return isPrime(result)
else:
return False
input_number = 42
output = check_for_moran_number(input_number)
print("{} is a Moran Number:{}".format(input_number, output))
input_number = 20
output = check_for_moran_number(input_number)
print("{} is a Moran Number:{}".format(input_number, output))
输出:
42 is a Moran Number:True
20 is a Moran Number:False
结论
在本文中,我们讨论了什么是莫兰数。我们还讨论了检查 Moran 数的步骤,并用 Python 实现了它。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。您可能还会喜欢这篇关于 python 中的复数的文章。
检查熊猫 Python 中的 NaN 值
原文:https://www.pythonforbeginners.com/basics/check-for-nan-values-in-pandas-python
在 python 中处理数据时,我们经常会遇到 null 值或 NaN 值。在本文中,我们将讨论在 pandas 数据帧或系列中检查 nan 值或 null 值的不同方法。
isna()函数
pandas 中的 isna()函数用于检查 NaN 值。它具有以下语法。
pandas.isna(object)
这里,object可以是单个 python 对象,也可以是 python 对象的列表/数组。
如果我们将一个 python 对象作为输入参数传递给 isna()方法,如果 python 对象是 None,pd,它将返回 True。NA 或 np。NaN 对象。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=pd.NA
print("The value is:",x)
output=pd.isna(x)
print("Is the value Null:",output)
输出:
The value is: <NA>
Is the value Null: True
在上面的例子中,我们已经超过了熊猫。NA 对象到isna() 函数。执行后,该函数返回 True。
当我们将元素的列表或 numpy 数组传递给 isna()函数时,isna()函数会对数组中的每个元素执行。
执行后,它返回一个包含真值和假值的列表或数组。输出数组的 False 值对应于在输入列表或数组中相同位置上不是 NA、NaN 或 None 的所有值。输出数组中的真值对应于输入列表或数组中相同位置的所有 NA、NaN 或 None 值。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=[1,2,pd.NA,4,5,None, 6,7,np.nan]
print("The values are:",x)
output=pd.isna(x)
print("Are the values Null:",output)
输出:
The values are: [1, 2, <NA>, 4, 5, None, 6, 7, nan]
Are the values Null: [False False True False False True False False True]
在这个例子中,我们将一个包含 9 个元素的列表传递给了isna()函数。执行后,isna()方法返回一个包含 9 个布尔值的列表。输出列表中的每个元素都与给isna() 函数的输入列表中相同索引处的元素相关联。在输入列表包含空值的索引处,输出列表包含 True。类似地,在输入列表包含整数的索引处,输出列表包含 False。
使用 isna()方法检查 Pandas 数据帧中的 NaN 值
除了isna()函数,pandas 模块在数据帧级别也有 isna() 方法。您可以直接调用熊猫数据帧上的isna()方法来检查 nan 值。
当在 pandas 数据帧上调用isna()方法时,它返回另一个包含真值和假值的数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
df=pd.read_csv("grade.csv")
print("The dataframe is:")
print(df)
output=df.isna()
print("Are the values Null:")
print(output)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
Are the values Null:
Class Roll Name Marks Grade
0 False False False False False
1 False False False True False
2 False False False False False
3 False False False True True
4 False False False False False
5 False False False False False
6 False False False False False
7 False False False True False
8 False False False False False
9 False False False True False
10 False False False False False
11 False False False True True
在上面的例子中,我们传递了一个包含 NaN 值和其他值的 dataframe。isna()方法返回包含布尔值的数据帧。这里,输出数据帧的假值对应于在输入数据帧中相同位置不是 NA、NaN 或 None 的所有值。输出数据帧中的真值对应于输入数据帧中相同位置的所有 NA、NaN 或 None 值。
检查熊猫数据框中某列的 Nan 值
除了整个数据帧,您还可以在 pandas 数据帧的一列中检查 nan 值。为此,您只需要调用特定列上的isna() 方法,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("grade.csv")
print("The dataframe column is:")
print(df["Marks"])
output=df["Marks"].isna()
print("Are the values Null:")
print(output)
输出:
The dataframe column is:
0 85.0
1 NaN
2 75.0
3 NaN
4 73.0
5 79.0
6 55.0
7 NaN
8 88.0
9 NaN
10 55.0
11 NaN
Name: Marks, dtype: float64
Are the values Null:
0 False
1 True
2 False
3 True
4 False
5 False
6 False
7 True
8 False
9 True
10 False
11 True
Name: Marks, dtype: bool
使用 isna()方法检查熊猫系列中的 Nan 值
像 dataframe 一样,我们也可以对 pandas 中的 Series 对象调用isna() 方法。在这种情况下,isna()方法返回一个包含真值和假值的序列。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=pd.Series([1,2,pd.NA,4,5,None, 6,7,np.nan])
print("The series is:")
print(x)
output=pd.isna(x)
print("Are the values Null:")
print(output)
输出:
The series is:
0 1
1 2
2 <NA>
3 4
4 5
5 None
6 6
7 7
8 NaN
dtype: object
Are the values Null:
0 False
1 False
2 True
3 False
4 False
5 True
6 False
7 False
8 True
dtype: bool
在这个例子中,我们在熊猫系列上调用了isna() 方法。isna() 方法在执行后返回一系列布尔值。这里,输出序列的假值对应于在输入序列中相同位置不是 NA、NaN 或 None 的所有值。输出序列中的真值对应于输入序列中相同位置的所有 NA、NaN 或 None 值。
使用 isnull()方法检查熊猫的 NaN 值
isnull() 函数是 isna() 函数的别名。因此,它的工作方式与 isna() 功能完全相同。
当我们传递一个 NaN 值时,熊猫。NA 值,熊猫。NaT 值,或者 None 对象为isnull() 函数,则返回 True。
import pandas as pd
import numpy as np
x=pd.NA
print("The value is:",x)
output=pd.isnull(x)
print("Is the value Null:",output)
输出:
The value is: <NA>
Is the value Null: True
在上面的例子中,我们已经过了熊猫。isnull()功能的 NA 值。因此,它返回 True。
当我们将任何其他 python 对象传递给isnull()函数时,它返回 False,如下所示。
import pandas as pd
import numpy as np
x=1117
print("The value is:",x)
output=pd.isnull(x)
print("Is the value Null:",output)
输出:
The value is: 1117
Is the value Null: False
在这个例子中,我们将值 1117 传递给了isnull()函数。因此,它返回 False,表明该值不是空值。
当我们将一个列表或 numpy 数组传递给isnull() 函数时,它返回一个包含 True 和 False 值的 numpy 数组。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=[1,2,pd.NA,4,5,None, 6,7,np.nan]
print("The values are:",x)
output=pd.isnull(x)
print("Are the values Null:",output)
输出:
The values are: [1, 2, <NA>, 4, 5, None, 6, 7, nan]
Are the values Null: [False False True False False True False False True]
在这个例子中,我们将一个列表传递给了isnull() 函数。执行后, isnull() 函数返回一个布尔值列表。输出列表中的每个元素都与给isnull() 函数的输入列表中相同索引处的元素相关联。在输入列表包含空值的索引处,输出列表包含 True。类似地,在输入列表包含整数的索引处,输出列表包含 False。
使用 isnull()方法检查数据帧中的 NaN 值
您还可以调用 pandas 数据帧上的isnull() 方法来检查 nan 值,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("grade.csv")
print("The dataframe is:")
print(df)
output=df.isnull()
print("Are the values Null:")
print(output)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
Are the values Null:
Class Roll Name Marks Grade
0 False False False False False
1 False False False True False
2 False False False False False
3 False False False True True
4 False False False False False
5 False False False False False
6 False False False False False
7 False False False True False
8 False False False False False
9 False False False True False
10 False False False False False
11 False False False True True
在输出中,您可以观察到isnull()方法的行为方式与isna() 方法完全相同。
使用 isnull()方法检查 Dataframe 中列的 NaN
除了整个数据帧,您还可以使用isnull()方法来检查列中的 nan 值,如下例所示。
import pandas as pd
import numpy as np
df=pd.read_csv("grade.csv")
print("The dataframe column is:")
print(df["Marks"])
output=df["Marks"].isnull()
print("Are the values Null:")
print(output)
输出:
The dataframe column is:
0 85.0
1 NaN
2 75.0
3 NaN
4 73.0
5 79.0
6 55.0
7 NaN
8 88.0
9 NaN
10 55.0
11 NaN
Name: Marks, dtype: float64
Are the values Null:
0 False
1 True
2 False
3 True
4 False
5 False
6 False
7 True
8 False
9 True
10 False
11 True
Name: Marks, dtype: bool
以类似的方式,您可以对 pandas 系列调用 isnull()方法,如下所示。
import pandas as pd
import numpy as np
x=pd.Series([1,2,pd.NA,4,5,None, 6,7,np.nan])
print("The series is:")
print(x)
output=pd.isnull(x)
print("Are the values Null:")
print(output)
输出:
The series is:
0 1
1 2
2 <NA>
3 4
4 5
5 None
6 6
7 7
8 NaN
dtype: object
Are the values Null:
0 False
1 False
2 True
3 False
4 False
5 True
6 False
7 False
8 True
dtype: bool
在上面的例子中,我们对一个系列调用了isnull()方法。isnull()方法在执行后返回一系列布尔值。这里,输出序列的假值对应于在输入序列中相同位置不是 NA、NaN 或 None 的所有值。输出序列中的真值对应于输入序列中相同位置的所有 NA、NaN 或 None 值。
结论
在这篇文章中,我们讨论了检查熊猫的 nan 值的不同方法。要了解更多关于 python 编程的知识,
你可以阅读这篇关于如何对熊猫数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
检查熊猫 Python 中的非空值
原文:https://www.pythonforbeginners.com/basics/check-for-not-null-value-in-pandas-python
在 python 中,我们有时需要过滤非空值和空值。在本文中,我们将使用示例讨论在 pandas 中检查 not null 的不同方法。
我们可以使用notna() 函数和 notnull()函数在 pandas 中检查 not null。让我们逐一讨论每个功能。
使用 notna()方法检查 Pandas 中的 Not Null
顾名思义,notna()方法是对isna()方法的否定。isna()方法用于检查熊猫的 nan 值。notna() 函数的语法如下。
pandas.notna(object)
这里,object可以是单个 python 对象,也可以是对象的集合,比如 python 列表或元组。
如果我们将一个 python 对象作为输入参数传递给notna() 方法,如果 python 对象是 None,pd,它将返回 False。NA 或 np。NaN 对象。对于不为空的 python 对象,notna()函数返回 True。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=pd.NA
print("The value is:",x)
output=pd.notna(x)
print("Is the value not Null:",output)
输出:
The value is: <NA>
Is the value not Null: False
在上面的例子中,我们已经超过了熊猫。NA 对象到notna()函数。因此,它返回 False。
当我们将元素的列表或 numpy 数组传递给notna() 函数时,notna()函数会对数组中的每个元素执行。执行后,它返回一个包含真值和假值的列表或数组。输出数组的真值对应于输入列表或数组中相同位置上所有不为 NA、NaN 或 None 的值。输出数组中的 False 值对应于输入列表或数组中相同位置的所有 NA、NaN 或 None 值。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=[1,2,pd.NA,4,5,None, 6,7,np.nan]
print("The values are:",x)
output=pd.notna(x)
print("Are the values not Null:",output)
输出:
The values are: [1, 2, <NA>, 4, 5, None, 6, 7, nan]
Are the values not Null: [ True True False True True False True True False]
在这个例子中,我们将一个包含 9 个元素的列表传递给了notna() 函数。执行后,notna() 函数返回一个包含 9 个布尔值的列表。输出列表中的每个元素都与给notna()函数的输入列表中相同索引处的元素相关联。在输入列表不包含空值的索引处,输出列表包含 True。类似地,在输入列表包含空值的索引处,输出列表包含 False。
使用 notna()方法检查熊猫数据帧中的 Not NA
除了notna()函数,python 还为我们提供了notna()方法来检查 pandas 数据帧和系列对象中的非空值。
当在熊猫数据帧上调用notna() 方法时,返回另一个包含真值和假值的数据帧。输出数据帧的真值对应于在输入数据帧中相同位置不是 NA、NaN 或 None 的所有值。输出数据帧中的假值对应于输入数据帧中相同位置的所有 NA、NaN 或 None 值。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
df=pd.read_csv("grade.csv")
print("The dataframe is:")
print(df)
output=df.notna()
print("Are the values not Null:")
print(output)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
Are the values not Null:
Class Roll Name Marks Grade
0 True True True True True
1 True True True False True
2 True True True True True
3 True True True False False
4 True True True True True
5 True True True True True
6 True True True True True
7 True True True False True
8 True True True True True
9 True True True False True
10 True True True True True
11 True True True False False
在上面的例子中,我们在包含 NaN 值和其他值的数据帧上调用了notna() 方法。notna()方法返回一个包含布尔值的数据帧。这里,输出数据帧的假值对应于在输入数据帧中相同位置为 NA、NaN 或 None 的所有值。输出数据帧中的真值对应于输入数据帧中相同位置的所有非空值。
检查 Pandas 数据帧中某列的非空值
除了整个数据帧,您还可以在 pandas 数据帧的列中检查 not null 值。为此,您只需要调用特定列上的notna()方法,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("grade.csv")
print("The dataframe column is:")
print(df["Marks"])
output=df["Marks"].notna()
print("Are the values not Null:")
print(output)
输出:
The dataframe column is:
0 85.0
1 NaN
2 75.0
3 NaN
4 73.0
5 79.0
6 55.0
7 NaN
8 88.0
9 NaN
10 55.0
11 NaN
Name: Marks, dtype: float64
Are the values not Null:
0 True
1 False
2 True
3 False
4 True
5 True
6 True
7 False
8 True
9 False
10 True
11 False
Name: Marks, dtype: bool
使用 notna()方法检查熊猫系列中的 Not NA
像 dataframe 一样,我们也可以在一个熊猫系列对象上调用notna() 方法。在这种情况下,notna()方法返回一个包含真值和假值的序列。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=pd.Series([1,2,pd.NA,4,5,None, 6,7,np.nan])
print("The series is:")
print(x)
output=pd.notna(x)
print("Are the values not Null:")
print(output)
输出:
The series is:
0 1
1 2
2 <NA>
3 4
4 5
5 None
6 6
7 7
8 NaN
dtype: object
Are the values not Null:
0 True
1 True
2 False
3 True
4 True
5 False
6 True
7 True
8 False
dtype: bool
在这个例子中,我们对熊猫系列调用了notna()方法。notna()方法在执行后返回一系列布尔值。这里,输出序列的假值对应于在输入序列中相同位置为 NA、NaN 或 None 的所有值。输出序列中的真值对应于输入序列中相同位置的所有非空值。
使用 notnull()方法检查 Pandas 中的 Not Null
notnull()方法是notna()方法的别名。因此,它的工作原理与notna()方法完全相同。
当我们传递一个 NaN 值时,熊猫。NA 值,熊猫。NaT 值,或者 None 对象为notnull() 函数,则返回 False。
import pandas as pd
import numpy as np
x=pd.NA
print("The value is:",x)
output=pd.notnull(x)
print("Is the value not Null:",output)
输出:
The value is: <NA>
Is the value not Null: False
在上面的例子中,我们已经过了熊猫。notnull()功能的 NA 值。因此,它返回 False。
当我们将任何其他 python 对象传递给notnull() 函数时,它返回 True,如下所示。
import pandas as pd
import numpy as np
x=1117
print("The value is:",x)
output=pd.notnull(x)
print("Is the value not Null:",output)
输出:
The value is: 1117
Is the value not Null: True
在这个例子中,我们将值 1117 传递给了notnull()函数。因此,它返回 True,表明该值不是空值。
当我们将一个列表或 numpy 数组传递给notnull()函数时,它返回一个包含 True 和 False 值的 numpy 数组。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=[1,2,pd.NA,4,5,None, 6,7,np.nan]
print("The values are:",x)
output=pd.notnull(x)
print("Are the values not Null:",output)
输出:
The values are: [1, 2, <NA>, 4, 5, None, 6, 7, nan]
Are the values not Null: [ True True False True True False True True False]
在这个例子中,我们将一个列表传递给了notnull() 函数。执行后,notnull() 函数返回一个布尔值列表。输出列表中的每个元素都与输入列表中相同索引处的元素相关联,该索引被赋予notnull()功能。在输入列表包含 Null 值的索引处,输出列表包含 False。类似地,在输入列表包含整数的索引处,输出列表包含 True。
使用 notnull()方法检查 Pandas 数据帧中的 Not Null
您还可以调用 pandas 数据帧上的notnull()方法来检查 nan 值,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("grade.csv")
print("The dataframe is:")
print(df)
output=df.notnull()
print("Are the values not Null:")
print(output)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris NaN A
2 1 14 Sam 75.0 B
3 1 15 Harry NaN NaN
4 2 22 Tom 73.0 B
5 2 15 Golu 79.0 B
6 2 27 Harsh 55.0 C
7 2 23 Clara NaN B
8 3 34 Amy 88.0 A
9 3 15 Prashant NaN B
10 3 27 Aditya 55.0 C
11 3 23 Radheshyam NaN NaN
Are the values not Null:
Class Roll Name Marks Grade
0 True True True True True
1 True True True False True
2 True True True True True
3 True True True False False
4 True True True True True
5 True True True True True
6 True True True True True
7 True True True False True
8 True True True True True
9 True True True False True
10 True True True True True
11 True True True False False
在输出中,您可以观察到notn ull()方法的行为方式与notna()方法完全相同。
除了整个 dataframe,您还可以使用notnull()方法来检查列中的 not nan 值,如下例所示。
import pandas as pd
import numpy as np
df=pd.read_csv("grade.csv")
print("The dataframe column is:")
print(df["Marks"])
output=df["Marks"].notnull()
print("Are the values not Null:")
print(output)
输出:
The dataframe column is:
0 85.0
1 NaN
2 75.0
3 NaN
4 73.0
5 79.0
6 55.0
7 NaN
8 88.0
9 NaN
10 55.0
11 NaN
Name: Marks, dtype: float64
Are the values not Null:
0 True
1 False
2 True
3 False
4 True
5 True
6 True
7 False
8 True
9 False
10 True
11 False
Name: Marks, dtype: bool
以类似的方式,您可以对 pandas 系列调用notnull() 方法,如下所示。
import pandas as pd
import numpy as np
x=pd.Series([1,2,pd.NA,4,5,None, 6,7,np.nan])
print("The series is:")
print(x)
output=pd.notnull(x)
print("Are the values not Null:")
print(output)
输出:
The series is:
0 1
1 2
2 <NA>
3 4
4 5
5 None
6 6
7 7
8 NaN
dtype: object
Are the values not Null:
0 True
1 True
2 False
3 True
4 True
5 False
6 True
7 True
8 False
dtype: bool
在上面的例子中,我们对一个系列调用了notnull()方法。notnull()方法在执行后返回一系列布尔值。这里,输出序列的真值对应于在输入序列中相同位置不是 NA、NaN 或 None 的所有值。输出序列中的假值对应于输入序列中相同位置的所有 NA、NaN 或 None 值。
结论
在本文中,我们讨论了在 pandas 中检查非空值的不同方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于如何对熊猫数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中检查裸体数字
原文:https://www.pythonforbeginners.com/basics/check-for-nude-number-in-python
你可能已经读过质数、合数、偶数、奇数等等。但是,你有没有想过什么是裸体数字?在本文中,我们将讨论什么是裸号。我们还将讨论一个 python 程序来检查一个数字是否是裸数字。
什么是裸号?
一个裸数是一个能被它的所有非零数字整除的数,也就是说,如果一个给定数中的所有数字都是这个数的因数,那么这个给定数就叫做裸数。
例如,24 可以被 2 和 4 整除。因此,24 是一个裸数字。相反,26 能被 2 整除,但不能被 6 整除。所以,这不是一个裸体数字。
现在,让我们尝试开发一种算法来检查一个裸体数字。
在 Python 中检查裸体数字
为了检查一个给定的数字是否是裸数字,我们首先必须提取它的所有数字。之后,我们需要用所有的数字除这个数。如果一个数不能被它的任何一位整除,我们就说给定的数不是裸数。否则,该号码将被宣布为裸号。
为了从给定的数字中提取数字,我们将首先创建一个集合来存储所有的数字。之后,我们将开始把给定的数除以 10。在每次除法运算中,数字最右边的数字将被提取为余数,并存储在集合中。我们将继续用 10 除这个数,并将余数存储在集合中,直到这个数变成 0。
def create_digits(N):
digits = set()
while N > 0:
digit = N % 10
N = N // 10
digits.add(digit)
return digits
input_number = 12345
digits = create_digits(input_number)
print("Digits in {} are {}.".format(input_number,digits))
输出:
Digits in 12345 are {1, 2, 3, 4, 5}.
提取所有数字后,我们将给定的数除以每个数字。如果任何数字不是给定数字的因子,我们将声明该数字不是裸数。永远记住,在除法运算中,我们只能考虑非零数字。否则,程序会出错。
检查裸体数字的整个 Python 程序如下。
def create_digits(N):
digits = set()
while N > 0:
digit = N % 10
N = N // 10
digits.add(digit)
return digits
def is_nude(N):
digits = create_digits(N)
for digit in digits:
if digit != 0 and N % digit != 0:
return False
return True
input_number = 12345
digits = create_digits(input_number)
output = is_nude(input_number)
print("Digits in {} are {}.".format(input_number, digits))
print("{} is a nude number:{}".format(input_number, output))
input_number = 24
output = is_nude(input_number)
digits = create_digits(input_number)
print("Digits in {} are {}.".format(input_number, digits))
print("{} is a nude number:{}".format(input_number, output))
输出:
Digits in 12345 are {1, 2, 3, 4, 5}.
12345 is a nude number:False
Digits in 24 are {2, 4}.
24 is a nude number:True
结论
在这篇文章中,我们讨论了什么是裸号。我们还讨论了检查给定数字是否为裸数字的算法,并用 python 实现了该算法。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。您可能还会喜欢这篇关于 python 中的复数的文章。
在 Python 中检查完全数
原文:https://www.pythonforbeginners.com/basics/check-for-perfect-number-in-python
我们根据他们的专业来命名数字。一个这样的数字是完美的数字。在本文中,我们将讨论完全数的性质。我们还将在 python 中实现一个检查完全数的程序。
什么是完美的数字?
如果一个数等于除该数本身之外的所有因子之和,则称该数为完全数。如果我们考虑和中的数本身,我们可以说一个完全数的所有因子之和是给定数的两倍。
例如,考虑数字 6。它有四个因素,即 1、2、3 和 6。因为我们排除了这个数字本身,所以其他因素(即 1、2 和 3)的总和是 6。因此,6 是一个完美的数字。
或者,6 的所有因子的和是 1+2+3+6,即 12,它是该数本身的两倍。因此,6 是一个完美的数字。
让我们来看另一个数字 10。10 的因数是 1,2,5 和 10。10 的所有因子之和等于 18,它不是给定数字的两倍。因此,10 不是一个完美的数字。
在 Python 中检查完全数
要检查一个完美的数字,我们首先要找到它的因子。之后,我们将检查所有因素的总和是否是给定数字的两倍。
求给定数 N 的因子,我们将该数除以从 1 到 N 的所有数,完全除给定数的数将被声明为 N 的因子,我们将这些因子存储在一个列表中,如下所示。
dedef calculate_factors(N):
factors = []
for i in range(1, N + 1):
if N % i == 0:
factors.append(i)
return factors
input_number = 10
output = calculate_factors(input_number)
print("factors of {} are {}".format(input_number, output))
输出:
factors of 10 are [1, 2, 5, 10]
找到给定数字的因子后,我们将使用 sum()函数找到因子的和。找到总和后,我们将检查总和是否是给定数字的两倍。如果是,我们就说给定的数是完全数。否则不会。
我们可以实现这个逻辑来检查 python 中的完全数,如下所示。
def calculate_factors(N):
factors = []
for i in range(1, N + 1):
if N % i == 0:
factors.append(i)
return factors
def check_perfect_number(N):
factors = calculate_factors(N)
sumOfFactors = sum(factors)
if sumOfFactors // 2 == N:
return True
else:
return False
input_number = 10
output = check_perfect_number(input_number)
print("{} is a perfect number: {}".format(input_number, output))
input_number = 6
output = check_perfect_number(input_number)
print("{} is a perfect number: {}".format(input_number, output))
输出:
10 is a perfect number: False
6 is a perfect number: True
结论
在这篇文章中,我们讨论了什么是完美的数字。我们还实现了一个程序来检查一个给定的数是否是一个完全数。想了解更多 python 中的数字,可以阅读这篇关于 python 中的十进制数字的文章。你可能也会喜欢这篇关于 python 中的复数的文章。
在 Python 中检查质数
原文:https://www.pythonforbeginners.com/basics/check-for-prime-number-in-python
质数是那些只有两个因子的数,即 1 和数本身。在本文中,我们将讨论在 python 中检查素数的两种方法。
什么是质数?
质数是那些大于一且只有两个因子的正整数。质数的例子有 2、3、5、7、11、13、17、19、23、29 等。
这里,
- 2 只有两个因子,即 1 和 2。
- 3 只有两个因子,即 1 和 3。
- 5 只有两个因子,即 1 和 5。
你可以观察到所有其他数字也只有两个因素。
在 Python 中检查质数
为了检验一个数是否是质数,我们只需确定所有大于 1 小于这个数本身的数都不是这个数的因数。为此,我们将定义一个函数 isPrime(),它接受数字 N 作为输入。然后使用循环的检查 2 和 N-1 之间的任何数是否是 N 的因数。如果存在一个因子,它将返回 False,表明输入的数字 N 不是质数。否则,它返回 True。
def isPrime(N):
for number in range(2, N):
if N % number == 0:
return False
return True
input_number = 23
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
input_number = 126
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
输出:
23 is a Prime number:True
126 is a Prime number:False
在上面的例子中,我们已经检查了从 2 到 N-1 的每一个数,看它是否是 N 的因子。我们可以通过检查数字直到 N/2 而不是 N-1 来优化这个过程。这是因为 N 大于 N/2 的唯一因素是 N 本身。因此,我们将只检查 N/2 之前的数字因子。此外,我们还可以检查一个数字是否是偶数。如果大于 2 的数是偶数,它就永远不是质数。我们可以使用下面给出的这些概念定义一个改进的 isPrime()函数。
def isPrime(N):
for number in range(2, N//2):
if N % number == 0:
return False
return True
input_number = 23
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
input_number = 126
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
输出:
23 is a Prime number:True
126 is a Prime number:False
我们可以使用简单的逻辑再次优化上面的程序。你可以观察到一个数的因子总是成对出现。对于一个数 N,因子可以配对为(1,N),(2,N/2),(3,N/3),(4,N/4)直到(N1/2,N^(1/2) )。因此,为了检查因子,我们可以只检查到 N^(1/2) 而不是 N/2。
例如,如果给我们一个数字 100,所有的因子都可以配对成(1,100)、(2,50)、(4,25)、(5,20)和(10,10)。在这里,如果 100 能被 2 整除,就一定能被 50 整除,如果 100 能被 4 整除,就一定能被 25 整除。我们不需要显式地检查一对数字中的两个数字来检查一个数字是否是因子。因此,为了检查质数,我们可以简单地使用一个 while 循环来检查一个因子直到 N^(1/2) 而不是 N/2。如果一个因子不在 2 和 N^(1/2)之间,这个数必须是一个质数。使用这个逻辑,我们可以如下修改上面示例中使用的 isPrime()函数。
def isPrime(N):
count = 2
while count ** 2 <= N:
if N % count == 0:
return False
count = count + 1
return True
input_number = 23
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
input_number = 126
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
输出:
23 is a Prime number:True
126 is a Prime number:False
结论
在本文中,我们讨论了 python 中检查素数的三种方法。要了解更多关于数字的知识,你可以阅读这篇关于 python 中的复数的文章。你可能也会喜欢这篇关于 Python 中的十进制数的文章。
在 Python 中检查排序列表
原文:https://www.pythonforbeginners.com/lists/check-for-sorted-list-in-python
列表是 python 中最常用的数据结构之一。在本文中,我们将讨论在 python 中检查排序列表的不同方法。
如何在 Python 中检查排序列表?
排序列表的所有元素都是按非降序排列的。换句话说,如果列表是排序列表,则索引 i 处的元素总是小于或等于索引i+1处的元素。例如,考虑下面的列表。
myList1=[1,2,3,4,5,6,7]
myList2=[1,2,3,3,4,5,5]
myList3=[1,2,3,4,2,5,6]
在这里,如果我们从左向右移动,myList1将所有元素按升序排列。因此,这是一个排序列表。myList2的元素不是按递增顺序排列的,但是如果我们从左向右移动,所有元素都是按非递减顺序排列的。于是,myList2也是一个排序列表。但是myList3中的元素既不是升序也不是非降序。因此,它不是一个排序列表。
在 Python 中检查排序列表
要检查一个排序列表,我们只需要遍历列表,检查所有的元素是否按非降序排列。为此,我们将使用一个变量isSorted和一个 For 循环。首先,假设列表已经排序,我们将初始化变量isSorted为True。之后,我们将遍历列表,检查从索引 0 到末尾,索引“i”处的所有元素是否都小于或等于索引“i+1”处的元素。如果我们发现索引“i”处的任何元素大于索引“i+1”处的元素,我们将把值False赋给isSorted变量,表示列表没有被排序。然后我们将使用 break 语句结束循环,因为我们已经发现列表没有排序。
如果我们找不到任何比它右边的元素大的元素,变量isSorted将保持True,并表示列表已排序。您可以在下面的示例中观察到这一点。
def checkSortedList(newList):
isSorted = True
l = len(newList)
for i in range(l - 1):
if newList[i] > newList[i + 1]:
isSorted = False
return isSorted
myList1 = [1, 2, 3, 4, 5, 6, 7]
myList2 = [1, 2, 3, 3, 4, 5, 5]
myList3 = [1, 2, 3, 4, 2, 5, 6]
print("The list {} is sorted: {} ".format(myList1, checkSortedList(myList1)))
print("The list {} is sorted: {} ".format(myList2, checkSortedList(myList2)))
print("The list {} is sorted: {} ".format(myList3, checkSortedList(myList3)))
输出:
The list [1, 2, 3, 4, 5, 6, 7] is sorted: True
The list [1, 2, 3, 3, 4, 5, 5] is sorted: True
The list [1, 2, 3, 4, 2, 5, 6] is sorted: False
结论
在本文中,我们已经讨论了如何检查排序列表。要了解更多关于列表的知识,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于用 python 理解字典的文章。
在 Python 中检查子集
原文:https://www.pythonforbeginners.com/basics/check-for-subset-in-python
python 中的集合是包含唯一不可变对象的数据结构。在本文中,我们将讨论什么是集合的子集,以及如何在 python 中检查子集。
什么是子集?
集合的子集是包含给定集合的部分或全部元素的另一个集合。换句话说,如果我们有一个集合 A 和集合 B,并且集合 B 的每个元素都属于集合 A,那么称集合 B 是集合 A 的子集。
让我们考虑一个例子,其中给我们三个集合 A、B 和 C,如下所示。
A={1,2,3,4,5,6,,7,8}
B={2,4,6,8}
C={0,1,2,3,4}
在这里,您可以观察到集合 B 中的所有元素都出现在集合 a 中。因此,集合 B 是集合 a 的子集。另一方面,集合 C 中的所有元素都不属于集合 a。因此,集合 C 不是集合 a 的子集。
您可以观察到,一个子集的元素总是少于或等于原始集合的元素。空集也被认为是任何给定集合的子集。现在,让我们描述一个在 python 中检查子集的逐步算法。
如何在 Python 中检查子集?
假设给了我们两个集合 A 和 B。现在,我们必须检查集合 B 是否是集合 A 的子集。为此,我们将遍历集合 B 中的所有元素,并检查它们是否出现在集合 A 中。如果集合 B 中存在一个不属于集合 A 的元素,我们就说集合 B 不是集合 A 的子集。否则,集合 B 就是集合 A 的子集。
为了在 Python 中实现这种方法,我们将使用一个 for 循环和一个标志变量isSubset。我们将把isSubset变量初始化为 True,表示集合 B 是集合 A 的子集。我们这样做是为了确保空的集合 B 也被认为是集合 A 的子集。在遍历集合 B 中的元素时,我们将检查该元素是否出现在集合 A 中。
如果我们找到了集合 A 中不存在的元素,我们将把False赋值给isSubset,表明集合 B 不是集合 A 的子集。
如果我们在集合 B 中没有发现任何不属于集合 A 的元素,isSubset变量将包含值True,表明集合 B 是集合 A 的子集。
def checkSubset(set1, set2):
isSubset = True
for element in set1:
if element not in set2:
isSubset = False
break
return isSubset
A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8}
C = {0, 1, 2, 3, 4}
print("Set {} is: {}".format("A", A))
print("Set {} is: {}".format("B", B))
print("Set {} is: {}".format("C", C))
print("Set B is subset of A :", checkSubset(B, A))
print("Set C is subset of A :", checkSubset(C, A))
print("Set B is subset of C :", checkSubset(B, C))
输出:
Set A is: {1, 2, 3, 4, 5, 6, 7, 8}
Set B is: {8, 2, 4, 6}
Set C is: {0, 1, 2, 3, 4}
Set B is subset of A : True
Set C is subset of A : False
Set B is subset of C : False
建议阅读:Python 中的聊天应用
使用 issubset()方法检查子集
我们还可以使用 issubset()方法来检查 python 中的子集。当对集合 A 调用 issubset()方法时,该方法接受集合 B 作为输入参数,如果集合 A 是 B 的子集,则返回True,否则返回False。
您可以使用 issubset()方法来检查 python 中的子集,如下所示。
A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8}
C = {0, 1, 2, 3, 4}
print("Set {} is: {}".format("A", A))
print("Set {} is: {}".format("B", B))
print("Set {} is: {}".format("C", C))
print("Set B is subset of A :", B.issubset(A))
print("Set C is subset of A :", C.issubset(A))
print("Set B is subset of C :", B.issubset(C))
输出:
Set A is: {1, 2, 3, 4, 5, 6, 7, 8}
Set B is: {8, 2, 4, 6}
Set C is: {0, 1, 2, 3, 4}
Set B is subset of A : True
Set C is subset of A : False
Set B is subset of C : False
结论
在本文中,我们讨论了在 python 中检查子集的方法。要了解更多关于集合的知识,你可以阅读这篇关于 python 中的集合理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
检查 Python 中的超集
原文:https://www.pythonforbeginners.com/basics/check-for-superset-in-python
在 python 中,我们使用集合来存储唯一的不可变对象。在本文中,我们将讨论什么是集合的超集。我们还将讨论在 Python 中检查超集的方法。
什么是超集?
集合的超集是包含给定集合的所有元素的另一个集合。换句话说,如果我们有一个集合 A 和集合 B,并且集合 B 的每个元素都属于集合 A,那么集合 A 被称为集合 B 的超集。
让我们考虑一个例子,其中给我们三个集合 A、B 和 C,如下所示。
A={1,2,3,4,5,6,7,8}
B={2,4,6,8}
C={0,1,2,3,4}
在这里,您可以观察到集合 B 中的所有元素都出现在集合 A 中。因此,集合 A 是集合 B 的超集。另一方面,集合 C 中的所有元素都不属于集合 A。因此,集合 A 不是集合 C 的超集。
您可以观察到超集总是比原始集拥有更多或相等的元素。现在,让我们描述一个在 python 中检查超集的逐步算法。
建议阅读:Python 中的聊天应用
如何在 Python 中检查超集?
假设给了我们两个集合 A 和 B。现在,我们必须检查集合 B 是否是集合 A 的超集。为此,我们将遍历集合 A 中的所有元素,并检查它们是否出现在集合 B 中。如果集合 A 中存在一个不属于集合 B 的元素,我们就说集合 B 不是集合 A 的超集。否则,集合 B 就是集合 A 的超集。
为了在 Python 中实现这种方法,我们将使用一个 for 循环和一个标志变量isSuperset。我们将初始化isSuperset变量为 True,表示集合 B 是集合 A 的超集。现在我们将使用 for 循环遍历集合 A。在遍历集合 A 中的元素时,我们将检查该元素是否出现在集合 B 中。
如果我们在 A 中发现了集合 B 中没有的元素,我们将把False赋值给isSuperset,表明集合 B 不是集合 A 的超集。
如果我们在集合 A 中没有发现任何不属于集合 B 的元素,isSuperset变量将包含值True,表明集合 B 是集合 A 的超集。
def checkSuperset(set1, set2):
isSuperset = True
for element in set2:
if element not in set1:
isSuperset = False
break
return isSuperset
A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8}
C = {0, 1, 2, 3, 4}
print("Set {} is: {}".format("A", A))
print("Set {} is: {}".format("B", B))
print("Set {} is: {}".format("C", C))
print("Set A is superset of B :", checkSuperset(A, B))
print("Set A is superset of C :", checkSuperset(A, C))
print("Set B is superset of C :", checkSuperset(B, C))
输出:
Set A is: {1, 2, 3, 4, 5, 6, 7, 8}
Set B is: {8, 2, 4, 6}
Set C is: {0, 1, 2, 3, 4}
Set A is superset of B : True
Set A is superset of C : False
Set B is superset of C : False
使用 issuperset()方法检查超集
我们还可以使用 issuperset()方法来检查 python 中的超集。当在集合 A 上调用issuperset()方法时,该方法接受集合 B 作为输入参数,如果集合 A 是 B 的超集,则返回True,否则返回False。
您可以使用issuperset()方法来检查 python 中的超集,如下所示。
A = {1, 2, 3, 4, 5, 6, 7, 8}
B = {2, 4, 6, 8}
C = {0, 1, 2, 3, 4}
print("Set {} is: {}".format("A", A))
print("Set {} is: {}".format("B", B))
print("Set {} is: {}".format("C", C))
print("Set A is superset of B :", A.issuperset(B))
print("Set A is superset of C :", A.issuperset(C))
print("Set B is superset of C :", B.issuperset(C))
输出:
Set A is: {1, 2, 3, 4, 5, 6, 7, 8}
Set B is: {8, 2, 4, 6}
Set C is: {0, 1, 2, 3, 4}
Set A is superset of B : True
Set A is superset of C : False
Set B is superset of C : False
结论
在本文中,我们讨论了在 python 中检查超集的两种方法。要了解更多关于集合的知识,你可以阅读这篇关于 python 中的集合理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
在 Python 中检查难看的数字
原文:https://www.pythonforbeginners.com/basics/check-for-ugly-number-in-python
你可能听说过自然数、质数、偶数和奇数。但是,你有没有想过什么是丑陋的数字?在这篇文章中,我们将讨论什么是丑陋的数字。我们还将编写一个程序来检查 python 中的难看数字。
什么是难看的数字?
如果一个数只有 2,3 和 5 个质因数,那么这个数就是难看的数。换句话说,如果一个数可以通过 2、3 或 5 的乘方得到,那么这个数就是难看的数。
例如,18 可以由 2¹x 3²得到。因此,这是一个丑陋的数字。同样,90 也是一个难看的数字,因为它可以被得到为 2¹x 3²x5¹。相反,126 不是一个难看的数字,因为它可以通过 2¹x 3²x7¹得到。这里,126 的质因数之一是 7。因此,这不是一个难看的数字。
现在,让我们制定一个算法来检查 Python 中的难看数字。
Python 中检查难看数字的算法
为了检查一个数是不是丑数,我们会对它进行重复除法。首先,我们将把给定的数反复除以 2。如果得到的数不能被 2 除尽,我们将检查这个数是否是 1。如果是 1,我们会说一个数是难看的数。否则,我们将对结果执行 3 的重复除法。一旦结果被 3 整除,我们将检查它是否是 1。如果是,我们会说给定的数是一个难看的数。否则,我们将对结果执行 5 的重复除法。一旦结式被 5 整除,我们将检查结式是否为 1。如果是的话,我们会说一个数字是一个丑陋的数字。否则,我们会说这个数字不是一个丑陋的数字。
现在让我们用 Python 实现这个想法
Python 程序检查难看的数字
这里,我们实现了一个函数 is_ugly(),使用 while 循环进行重复除法,使用 if-else 语句进行条件检查。该函数将一个整数作为输入参数,如果输入的数字是一个难看的数字,则返回 True。否则,它返回 False。
def is_ugly(N):
while N % 2 == 0:
N = N // 2
if N == 1:
return True
while N % 3 == 0:
N = N // 3
if N == 1:
return True
while N % 5 == 0:
N = N // 5
if N == 1:
return True
return False
input_number = 18
output = is_ugly(input_number)
print("{} is an ugly number:{}".format(input_number, output))
input_number = 126
output = is_ugly(input_number)
print("{} is an ugly number:{}".format(input_number, output))
输出:
18 is an ugly number:True
126 is an ugly number:False
结论
在本文中,我们讨论并实现了一个程序来检查一个给定的数字是否是一个丑陋的数字。要了解更多关于 python 中的数字,你可以阅读这篇关于 python 中的十进制数字的文章。您可能还会喜欢这篇关于 python 中的复数的文章。
检查熊猫数据框架中的列是否排序
原文:https://www.pythonforbeginners.com/basics/check-if-a-column-is-sorted-in-a-pandas-dataframe
Pandas dataframe 是用 python 处理表格数据的一个很好的工具。在本文中,我们将讨论不同的方法来检查一个列是否在 pandas 数据帧中排序。
检查是否使用列属性对列进行排序
为了检查一个列是否在熊猫数据帧中按升序排序,我们可以使用该列的is_monotonic属性。如果列按升序排序,即如果列中的值单调递增,则is_monotonic属性的计算结果为True。
例如,如果数据帧按升序排序,is_monotonic属性将计算为 True,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv")
df.sort_values(by="Marks",inplace=True)
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
7 3 11 Bobby 50 D
0 2 27 Harsh 55 C
5 3 27 Aditya 55 C
1 2 23 Clara 78 B
4 3 15 Prashant 78 B
6 3 23 Radheshyam 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
The 'Marks' column is sorted: True
在上面的例子中,我们首先使用read_csv()函数将一个 CSV 文件加载到一个数据帧中。之后,我们使用sort_values() 方法按照"Marks"列对数据帧进行排序。排序后,可以观察到该列的is_monotonic属性返回 True。它表示该列按降序排序。
如果一列按降序排序,is_monotonic属性的计算结果将为 False。
import pandas as pd
df=pd.read_csv("grade2.csv")
df.sort_values(by="Marks",inplace=True,ascending=False)
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
3 3 34 Amy 88 A
2 3 33 Tina 82 A
1 2 23 Clara 78 B
4 3 15 Prashant 78 B
6 3 23 Radheshyam 78 B
0 2 27 Harsh 55 C
5 3 27 Aditya 55 C
7 3 11 Bobby 50 D
The 'Marks' column is sorted: False
在本例中,我们已经按降序对"Marks"列进行了排序。因此,is_monotonic属性的计算结果为 False。
如果 dataframe 中的某一列没有排序,is_monotonic属性的计算结果将为 False。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
The 'Marks' column is sorted: False
在这里,您可以观察到我们已经访问了 is_monotonic 属性,而没有按照"Marks" 列对 dataframe 进行排序。因此,"Marks" 列是未排序的,并且is_monotonic属性的计算结果为 False。
is_monotonic不支持NaN值。如果一列包含NaN值,那么is_monotonic属性的计算结果总是假。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade.csv")
df.sort_values(by="Marks",inplace=True,ascending=True)
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
6 2 27 Harsh 55.0 C
10 3 27 Aditya 55.0 C
4 2 22 Tom 73.0 B
2 1 14 Sam 75.0 B
5 2 15 Golu 79.0 B
0 1 11 Aditya 85.0 A
8 3 34 Amy 88.0 A
1 1 12 Chris NaN A
3 1 15 Harry NaN NaN
7 2 23 Clara NaN B
9 3 15 Prashant NaN B
11 3 23 Radheshyam NaN NaN
The 'Marks' column is sorted: False
在这个例子中,您可以观察到"Marks"列包含了NaN值。因此,即使在排序之后,is_monotonic属性的计算结果也是假的。您可能会认为 NaN 值在列的最后。也许,这就是为什么is_monotonic属性评估为 False。
但是,如果我们将具有 NaN 值的行放在 dataframe 的顶部,is_monotonic属性将再次计算为 False。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade.csv")
df.sort_values(by="Marks",inplace=True,ascending=True,na_position="first")
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
1 1 12 Chris NaN A
3 1 15 Harry NaN NaN
7 2 23 Clara NaN B
9 3 15 Prashant NaN B
11 3 23 Radheshyam NaN NaN
6 2 27 Harsh 55.0 C
10 3 27 Aditya 55.0 C
4 2 22 Tom 73.0 B
2 1 14 Sam 75.0 B
5 2 15 Golu 79.0 B
0 1 11 Aditya 85.0 A
8 3 34 Amy 88.0 A
The 'Marks' column is sorted: False
在本例中,我们将 NaN 值放在排序后的"Marks"列的开头。即使在这之后,is_monotonic属性的计算结果也是 False。因此,我们可以得出结论,is_monotonic属性不能用于具有 NaN 值的列。
在使用is_monotonic属性时,您将得到一个FutureWarning,并显示消息“future warning:is _ monotonic 已被否决,并将在未来版本中被删除。请改用 is_monotonic_increasing。因此,在未来的熊猫版本中,is_monotonic属性将被弃用。作为替代,我们可以使用is_monotonic_increasing和is_monotonic_decreasing属性来检查熊猫数据帧中的列是否排序。
检查数据帧中的列是否按升序排序
要检查数据帧中的列是否按升序排序,我们可以使用is_monotonic_increasing属性。如果一个列按升序排序,那么is_monotonic_increasing属性的计算结果为 True。否则,它被设置为 False。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
df.sort_values(by="Marks",inplace=True,ascending=True)
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_increasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
7 3 11 Bobby 50 D
0 2 27 Harsh 55 C
5 3 27 Aditya 55 C
1 2 23 Clara 78 B
4 3 15 Prashant 78 B
6 3 23 Radheshyam 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
The 'Marks' column is sorted: True
如果一列没有排序,is_monotonic_increasing属性的计算结果为 False。
import pandas as pd
df=pd.read_csv("grade2.csv")
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_increasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
The 'Marks' column is sorted: False
此外,如果一列按降序排序,is_monotonic_increasing属性的计算结果为 False。
import pandas as pd
df=pd.read_csv("grade2.csv")
df.sort_values(by="Marks",inplace=True,ascending=False)
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_increasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
3 3 34 Amy 88 A
2 3 33 Tina 82 A
1 2 23 Clara 78 B
4 3 15 Prashant 78 B
6 3 23 Radheshyam 78 B
0 2 27 Harsh 55 C
5 3 27 Aditya 55 C
7 3 11 Bobby 50 D
The 'Marks' column is sorted: False
is_monotonic_increasing属性不能用于具有 NaN 值的列。如果一个列有 NaN 值,那么is_monotonic_increasing属性的计算结果总是 False。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade.csv")
df.sort_values(by="Marks",inplace=True,ascending=True,na_position="last")
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_increasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
6 2 27 Harsh 55.0 C
10 3 27 Aditya 55.0 C
4 2 22 Tom 73.0 B
2 1 14 Sam 75.0 B
5 2 15 Golu 79.0 B
0 1 11 Aditya 85.0 A
8 3 34 Amy 88.0 A
1 1 12 Chris NaN A
3 1 15 Harry NaN NaN
7 2 23 Clara NaN B
9 3 15 Prashant NaN B
11 3 23 Radheshyam NaN NaN
The 'Marks' column is sorted: False
即使我们将具有 NaN 值的行放在数据帧的顶部,is_monotonic_increasing属性的计算结果也将为 False。
import pandas as pd
df=pd.read_csv("grade.csv")
df.sort_values(by="Marks",inplace=True,ascending=True,na_position="first")
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_increasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
1 1 12 Chris NaN A
3 1 15 Harry NaN NaN
7 2 23 Clara NaN B
9 3 15 Prashant NaN B
11 3 23 Radheshyam NaN NaN
6 2 27 Harsh 55.0 C
10 3 27 Aditya 55.0 C
4 2 22 Tom 73.0 B
2 1 14 Sam 75.0 B
5 2 15 Golu 79.0 B
0 1 11 Aditya 85.0 A
8 3 34 Amy 88.0 A
The 'Marks' column is sorted: False
检查熊猫数据框中的列是否按降序排列
为了检查 pandas 数据帧中的列是否按降序排序,我们将使用is_monotonic_decreasing属性。如果按降序对列进行排序,则is_monotonic_decreasing属性的计算结果为 True。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade2.csv")
df.sort_values(by="Marks",inplace=True,ascending=False)
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_decreasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
3 3 34 Amy 88 A
2 3 33 Tina 82 A
1 2 23 Clara 78 B
4 3 15 Prashant 78 B
6 3 23 Radheshyam 78 B
0 2 27 Harsh 55 C
5 3 27 Aditya 55 C
7 3 11 Bobby 50 D
The 'Marks' column is sorted: True
如果一列未排序或按升序排序,则is_monotonic_decreasing属性的计算结果为 False,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv")
#df.sort_values(by="Marks",inplace=True,ascending=False)
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_decreasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
The 'Marks' column is sorted: False
is_monotonic_decreasing不能用于具有 NaN 值的列。如果一个列有 NaN 值,那么is_monotonic_decreasing属性的计算结果总是 False。您可以在下面的示例中观察到这一点。
import pandas as pd
df=pd.read_csv("grade.csv")
df.sort_values(by="Marks",inplace=True,ascending=False,na_position="last")
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_decreasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
8 3 34 Amy 88.0 A
0 1 11 Aditya 85.0 A
5 2 15 Golu 79.0 B
2 1 14 Sam 75.0 B
4 2 22 Tom 73.0 B
6 2 27 Harsh 55.0 C
10 3 27 Aditya 55.0 C
1 1 12 Chris NaN A
3 1 15 Harry NaN NaN
7 2 23 Clara NaN B
9 3 15 Prashant NaN B
11 3 23 Radheshyam NaN NaN
The 'Marks' column is sorted: False
即使我们将具有 NaN 值的行放在数据帧的顶部,is_monotonic_decreasing属性的计算结果也将为 False。
import pandas as pd
df=pd.read_csv("grade.csv")
df.sort_values(by="Marks",inplace=True,ascending=False,na_position="first")
print("The dataframe is:")
print(df)
temp=df["Marks"].is_monotonic_decreasing
print("The 'Marks' column is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Marks Grade
1 1 12 Chris NaN A
3 1 15 Harry NaN NaN
7 2 23 Clara NaN B
9 3 15 Prashant NaN B
11 3 23 Radheshyam NaN NaN
8 3 34 Amy 88.0 A
0 1 11 Aditya 85.0 A
5 2 15 Golu 79.0 B
2 1 14 Sam 75.0 B
4 2 22 Tom 73.0 B
6 2 27 Harsh 55.0 C
10 3 27 Aditya 55.0 C
The 'Marks' column is sorted: False
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
使用 Numpy 模块检查数据帧中的列是否排序
python 中的 numpy 模块为我们提供了不同的函数来对数值数据执行操作。一个这样的函数是diff()函数。diff()函数将 iterable 对象作为其输入参数,并返回一个包含数组元素的一阶差的数组,如下例所示。
import numpy as np
df=pd.read_csv("grade2.csv")
marks=df["Marks"]
print("The Marks column is:")
print(marks)
temp=np.diff(marks)
print("Array returned by diff() is:")
print(temp)
输出:
The Marks column is:
0 55
1 78
2 82
3 88
4 78
5 55
6 78
7 50
Name: Marks, dtype: int64
Array returned by diff() is:
[ 23 4 6 -10 -23 23 -28]
在这里,您可以观察到一阶差被计算为输入数组中(n+1)th和第 n 个元素的差。例如,输出数组的第一个元素是输入"Marks"列的第二个元素和第一个元素之差。输出数组中的第二个元素是第三个元素和"Marks"列的第二个元素的差。
通过观察输出,我们可以得出结论“如果‘Marks’列按升序排序,输出数组中的所有值都将大于或等于 0。同样,如果‘marks’列按降序排序,输出数组中的所有元素都将小于或等于 0。我们将使用这个结论来检查该列是按升序还是降序排序的。
要检查 pandas 数据帧的一列是否按升序排序,我们将使用以下步骤。
- 首先,我们将计算指定列的一阶差分。为此,我们将把列作为输入参数传递给
diff()函数。 - 之后,我们将检查输出数组中的所有元素是否都小于或等于 0。为此,我们将使用比较运算符和
all()方法。当我们在 numpy 数组上使用比较运算符时,我们会得到一个布尔值数组。在包含布尔值的数组上调用all()方法时,如果所有元素都为真,则返回True。 - 如果
all()方法返回 True,它将断定所有的元素都按升序排序。
您可以在下面的示例中观察到这一点。
import numpy as np
df=pd.read_csv("grade2.csv")
df.sort_values(by="Marks",inplace=True,ascending=True)
marks=df["Marks"]
print("The dataframe is:")
print(df)
temp=np.diff(marks)
print("Array returned by diff() is:")
print(temp)
boolean_array= temp>=0
print("Boolean array is:")
print(boolean_array)
result=boolean_array.all()
if result:
print("The marks column is sorted.")
else:
print("The marks column is not sorted.")
输出:
The dataframe is:
Class Roll Name Marks Grade
7 3 11 Bobby 50 D
0 2 27 Harsh 55 C
5 3 27 Aditya 55 C
1 2 23 Clara 78 B
4 3 15 Prashant 78 B
6 3 23 Radheshyam 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
Array returned by diff() is:
[ 5 0 23 0 0 4 6]
Boolean array is:
[ True True True True True True True]
The marks column is sorted.
为了检查一列是否按降序排序,我们将检查diff() 函数的输出数组中的所有元素是否都小于或等于 0。为此,我们将使用比较运算符和all()方法。当我们在 numpy 数组上使用比较运算符时,我们会得到一个布尔值数组。在包含布尔值的数组上调用all() 方法时,如果所有元素都为真,则返回真。
如果all()方法返回 True,它将得出结论,所有元素都按降序排序。您可以在下面的示例中观察到这一点。
import numpy as np
df=pd.read_csv("grade2.csv")
df.sort_values(by="Marks",inplace=True,ascending=False)
marks=df["Marks"]
print("The dataframe is:")
print(df)
temp=np.diff(marks)
print("Array returned by diff() is:")
print(temp)
boolean_array= temp<=0
print("Boolean array is:")
print(boolean_array)
result=boolean_array.all()
if result:
print("The marks column is sorted.")
else:
print("The marks column is not sorted.")
输出:
The dataframe is:
Class Roll Name Marks Grade
3 3 34 Amy 88 A
2 3 33 Tina 82 A
1 2 23 Clara 78 B
4 3 15 Prashant 78 B
6 3 23 Radheshyam 78 B
0 2 27 Harsh 55 C
5 3 27 Aditya 55 C
7 3 11 Bobby 50 D
Array returned by diff() is:
[ -6 -4 0 0 -23 0 -5]
Boolean array is:
[ True True True True True True True]
The marks column is sorted.
检查数据帧中的索引列是否已排序
要检查数据帧的索引是否按升序排序,我们可以使用如下所示的index属性和is_monotonic属性。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
df.sort_index(inplace=True,ascending=True)
print("The dataframe is:")
print(df)
temp=df.index.is_monotonic
print("The Index is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Grade
Marks
50 3 11 Bobby D
55 2 27 Harsh C
55 3 27 Aditya C
78 2 23 Clara B
78 3 15 Prashant B
78 3 23 Radheshyam B
82 3 33 Tina A
88 3 34 Amy A
The Index is sorted: True
要检查数据帧的索引是否按升序排序,我们可以使用 index 属性和is_monotonic_increasing属性,如下所示。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
df.sort_index(inplace=True,ascending=True)
print("The dataframe is:")
print(df)
temp=df.index.is_monotonic_increasing
print("The Index is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Grade
Marks
50 3 11 Bobby D
55 2 27 Harsh C
55 3 27 Aditya C
78 2 23 Clara B
78 3 15 Prashant B
78 3 23 Radheshyam B
82 3 33 Tina A
88 3 34 Amy A
The Index is sorted: True
要检查数据帧的索引是否按降序排序,我们可以使用如下所示的index属性和is_monotonic_decreasing属性。
import pandas as pd
df=pd.read_csv("grade2.csv",index_col="Marks")
df.sort_index(inplace=True,ascending=False)
print("The dataframe is:")
print(df)
temp=df.index.is_monotonic_decreasing
print("The Index is sorted:",temp)
输出:
The dataframe is:
Class Roll Name Grade
Marks
88 3 34 Amy A
82 3 33 Tina A
78 2 23 Clara B
78 3 15 Prashant B
78 3 23 Radheshyam B
55 2 27 Harsh C
55 3 27 Aditya C
50 3 11 Bobby D
The Index is sorted: True
您需要记住,如果索引列包含 NaN 值,那么is_monotonic属性、is_monotonic_increasing属性和is_monotonic_decreasing总是返回 False。因此,如果索引列包含 NaN 值,则不能使用这些属性来检查索引是否已排序。
结论
在本文中,我们讨论了检查 pandas 数据帧中的列是否排序的不同方法。为此,我们使用了 pandas 库以及 numpy 模块。我们还检查了熊猫数据帧的索引是否排序。
要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
检查 Python 中的字典中是否存在某个键
原文:https://www.pythonforbeginners.com/basics/check-if-a-key-exists-in-a-dictionary-in-python
我们使用 python 字典来存储键值对。有时,我们需要检查字典中是否存在某个键。在本 python 教程中,我们将通过工作示例讨论不同的方法来检查一个键是否存在于 python 中的给定字典中。
使用 get()方法检查字典中是否存在一个键
get()方法
当在 python 字典上调用get()方法时,该方法将一个键作为输入参数,并返回字典中与该键相关联的值。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
print("The input key is:", key)
value = myDict.get(key)
print("The associated value is:", value)
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: name
The associated value is: Python For Beginners
如果字典中没有这个键, get()方法返回如下所示的None。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "Aditya"
print("The input key is:", key)
value = myDict.get(key)
print("The associated value is:", value)
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: Aditya
The associated value is: None
在这里,您可以看到关键字'Aditya'在字典中不存在。因此,get()方法返回值None。
为了使用 get()方法检查给定的特定键是否存在于字典中,我们将调用字典上的get() 方法,并将该键作为输入参数传递。如果get()方法返回None,我们会说这个键在字典中不存在。否则,我们会说关键字存在于字典中。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "Aditya"
print("The input key is:", key)
value = myDict.get(key)
if value is None:
print("The key doesn't exist in the dictionary.")
else:
print("The key exists in the dictionary.")
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: Aditya
The key doesn't exist in the dictionary.
上面的方法只有在字典中没有键具有与之相关联的值None时才有效。如果一个键的值是None,程序会给出错误的结果。例如,看看下面的源代码。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog","Aditya":None}
print("The dictionary is:")
print(myDict)
key = "Aditya"
print("The input key is:", key)
value = myDict.get(key)
if value is None:
print("The key doesn't exist in the dictionary.")
else:
print("The key exists in the dictionary.")
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'Aditya': None}
The input key is: Aditya
The key doesn't exist in the dictionary.
在这里,您可以观察到关键字'Aditya'出现在字典中。但是,程序给出了一个错误的结果,说字典中没有这个键。这是因为关键字'Aditya'在字典中的关联值是None。
使用 get()方法检查字典中是否存在多个键
给定一个键列表,如果我们需要检查一个字典中是否存在多个键,我们将遍历这个键列表。迭代时,我们将调用字典上的 get() 方法,将当前键作为其输入参数。
在 for 循环中,如果get() 方法返回None,我们会说这个键在字典中不存在。否则,我们会说关键字存在于字典中。
您可以在下面的示例中观察这个过程。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = ["Aditya","name","url"]
print("The input keys are:", keys)
for key in keys:
value = myDict.get(key)
if value is None:
print("The key '{}' doesn't exist in the dictionary.".format(key))
else:
print("The key '{}' exists in the dictionary.".format(key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input keys are: ['Aditya', 'name', 'url']
The key 'Aditya' doesn't exist in the dictionary.
The key 'name' exists in the dictionary.
The key 'url' exists in the dictionary.
使用 get()方法检查字典列表中是否存在一个键
为了检查字典列表中是否存在某个键,我们将使用 for 循环来遍历字典列表。迭代时,我们将调用每个字典上的get()方法,将键作为输入参数。
如果任何一个字典返回一个不同于None的值,我们就说这个键存在于字典列表中。一旦找到密钥,我们将使用 break 语句来结束循环。
如果get()方法为一个字典返回None,我们将使用 continue 语句移动到下一个字典。
如果get()方法为所有的字典返回 None,我们会说这个键不在字典列表中。您可以在下面的示例中观察到这一点。
listOfDicts = [{1: 1, 2: 4, 3: 9},
{"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
"type": "python blog"},
{"person": "Aditya", "Country": "India"}
]
key = "Aditya"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
value = dictionary.get(key)
if value is not None:
print("The key '{}' is present in the list of dictionaries.".format(key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' is not present in the list of dictionaries.".format(key))
输出:
The key is: Aditya
The key 'Aditya' is not present in the list of dictionaries.
使用 for 循环检查字典中是否存在某个键
使用get()方法具有很高的时间复杂度,因为我们需要检索与每个键相关联的值。我们可以通过直接检查字典中是否存在键或者不使用 for 循环来避免这种情况,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "url"
print("The input key is:", key)
keyFound = False
for keys in myDict:
if keys == key:
print("The key '{}' is present in the dictionary.".format(key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' is not present in the dictionary.".format(key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: url
The key 'url' is present in the dictionary.
这里,字典作为包含键的容器对象工作。我们遍历迭代器,逐个检查字典中是否存在所需的键。
使用 for 循环检查字典中是否存在多个键
为了检查字典中是否存在多个键,我们将遍历键列表。在迭代输入键时,我们将迭代字典来检查每个输入键是否都存在于字典中。
如果在字典中找到一个键,我们就说这个键存在于字典中。否则不会。
一旦在字典中找到一个键,我们将使用 break 语句从内部 for 循环中出来。
在检查字典中是否存在某个键之后,我们将移动到下一个键,并重复相同的过程。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for key in input_keys:
keyFound = False
for keys in myDict:
if keys == key:
print("The key '{}' is present in the dictionary.".format(key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' is not present in the dictionary.".format(key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input keys are: ['Aditya', 'name', 'url']
The key 'Aditya' is not present in the dictionary.
The key 'name' is present in the dictionary.
The key 'url' is present in the dictionary.
使用 for 循环检查字典列表中是否存在某个键
为了检查一个键是否存在于字典列表中,我们将首先使用循环的遍历字典列表中的每个字典。在迭代时,我们将使用另一个 for 循环来检查输入键是否存在于字典中。一旦我们发现该键存在于字典中,我们将打印出该键存在于字典列表中。之后,我们将使用 break 语句跳出 for 循环。
如果字典列表中的字典都没有输入键,我们将打印出字典中不存在该键。您可以在下面的示例中观察到这一点。
listOfDicts = [{1: 1, 2: 4, 3: 9},
{"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
"type": "python blog"},
{"person": "Aditya", "Country": "India"}
]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
for keys in dictionary:
if keys == key:
print("The key '{}' is present in the list of dictionaries.".format(key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' is not present in the list of dictionaries.".format(key))
输出:
The key is: name
The key 'name' is present in the list of dictionaries.
使用成员运算符检查字典中是否存在某个键
成员操作符(in operator) 用于检查容器对象中是否存在元素。
要检查字典中是否存在某个键,我们可以使用如下所示的 in 操作符。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "Aditya"
print("The input key is:", key)
if key in myDict:
print("The key '{}' is present in the dictionary.".format(key))
else:
print("The key '{}' is not present in the dictionary.".format(key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input key is: Aditya
The key 'Aditya' is not present in the dictionary.
使用成员运算符检查字典中是否存在多个键
为了检查字典中是否存在多个键,我们将使用 for 循环和成员操作符。我们将使用 for 循环遍历键列表。迭代时,我们将使用成员操作符检查字典中是否存在一个键。如果我们发现一个键存在于字典中,我们会说这个键存在于字典中。否则不会。
您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for key in input_keys:
if key in myDict:
print("The key '{}' is present in the dictionary.".format(key))
else:
print("The key '{}' is not present in the dictionary.".format(key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input keys are: ['Aditya', 'name', 'url']
The key 'Aditya' is not present in the dictionary.
The key 'name' is present in the dictionary.
The key 'url' is present in the dictionary.
使用成员操作符检查一个键是否存在于 Python 中的字典列表中
给定一个字典列表,如果我们需要检查一个键是否存在于字典中,我们将使用下面的过程。
我们将使用 for 循环遍历字典列表。迭代时,我们将使用成员操作符检查每个字典中是否存在该键。如果我们在现在的字典里找不到答案,我们就要去下一本字典。一旦我们发现这个键存在于字典中,我们将打印出这个键存在于字典中。之后,我们将使用 break 语句跳出循环。
如果我们在任何一本词典中都找不到关键字,我们将在最后打印出来。您可以在下面的示例中观察到这一点。
listOfDicts = [{1: 1, 2: 4, 3: 9},
{"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
"type": "python blog"},
{"person": "Aditya", "Country": "India"}
]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
if key in dictionary:
print("The key '{}' is present in the list of dictionaries.".format(key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' is not present in the list of dictionaries.".format(key))
输出:
The key is: name
The key 'name' is present in the list of dictionaries.
使用 keys()方法检查字典中是否存在某个键
keys()方法
在字典上调用keys()方法时,它返回包含字典中所有键的dict_keys对象的副本,如下面的 python 脚本所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys=myDict.keys()
print("The keys are:", keys)
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys are: dict_keys(['name', 'url', 'acronym', 'type'])
为了使用keys()方法检查特定的键是否存在于字典中,我们将首先获得dict_keys对象。之后,我们将使用 for 循环遍历dict_keys对象。迭代时,我们将检查当前键是否是我们正在搜索的键。如果是,我们会说这个键在字典里。否则不会。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys are:", keys)
input_key = "url"
keyFound = False
for key in keys:
if key == input_key:
print("The key '{}' exists in the dictionary.".format(input_key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' does not exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys are: dict_keys(['name', 'url', 'acronym', 'type'])
The key 'url' exists in the dictionary.
除了使用 for 循环,我们还可以使用 membership 操作符来检查字典中是否存在该键,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys are:", keys)
input_key = "url"
if input_key in keys:
print("The key '{}' exists in the dictionary.".format(input_key))
else:
print("The key '{}' doesn't exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys are: dict_keys(['name', 'url', 'acronym', 'type'])
The key 'url' exists in the dictionary.
使用 Keys()方法检查字典中是否存在多个键
为了检查字典中是否存在多个键,我们将遍历输入键的列表。对于每个键,我们将使用成员操作符来检查该键是否存在于由keys()方法返回的dict_key对象中。如果是,我们将打印出该键存在于字典中。否则,我们将打印出该键不存在。最后,我们将转到下一个键。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys are:", keys)
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for input_key in input_keys:
if input_key in keys:
print("The key '{}' exists in the dictionary.".format(input_key))
else:
print("The key '{}' doesn't exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys are: dict_keys(['name', 'url', 'acronym', 'type'])
The input keys are: ['Aditya', 'name', 'url']
The key 'Aditya' doesn't exist in the dictionary.
The key 'name' exists in the dictionary.
The key 'url' exists in the dictionary.
使用 keys()方法检查字典列表中是否存在某个键
为了使用keys()方法检查一个键是否存在于字典列表中,我们将使用下面的过程。
- 我们将使用 for 循环遍历字典列表。
- 在对字典进行迭代时,我们将首先使用
keys()方法获得字典的键列表。之后,我们将使用成员操作符来检查输入键是否出现在键列表中。 - 如果这个键出现在列表中,我们将打印出来。之后,我们将使用 break 语句跳出 for 循环。
- 如果我们在当前的键列表中没有找到该键,我们将使用 continue 语句移动到字典列表中的下一个字典。
- 在遍历了所有的字典之后,如果我们没有找到这个键,我们将打印出这个键在字典中不存在。
您可以在下面的示例中观察整个过程。
listOfDicts = [{1: 1, 2: 4, 3: 9},
{"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
"type": "python blog"},
{"person": "Aditya", "Country": "India"}
]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
keys = dictionary.keys()
if key in keys:
print("The key '{}' is present in the list of dictionaries.".format(key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' is not present in the list of dictionaries.".format(key))
输出:
The key is: name
The key 'name' is present in the list of dictionaries.
使用 viewkeys()方法检查字典中是否存在某个键
在 python 版本中,我们可以使用viewkeys()方法代替 keys 方法来检查字典中是否存在某个键。
viewkeys()方法
在 python 字典上调用viewkeys()方法时,会返回包含字典键的dict_key对象的视图,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys=myDict.viewkeys()
print("The keys are:", keys)
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The keys are:', dict_keys(['url', 'acronym', 'type', 'name']))
为了使用viewkeys()方法检查指定的键是否存在于字典中,我们将首先使用viewkeys() 方法获得dict_keys对象。之后,我们将使用 for 循环遍历dict_keys对象。
迭代时,我们将检查当前键是否是我们正在搜索的键。如果是,我们会说这个键在字典里。否则不会。您可以在下面的代码中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.viewkeys()
print("The keys are:", keys)
input_key = "url"
keyFound = False
for key in keys:
if key == input_key:
print("The key '{}' exists in the dictionary.".format(input_key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' does not exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The keys are:', dict_keys(['url', 'acronym', 'type', 'name']))
The key 'url' exists in the dictionary.
除了使用 for 循环,我们还可以使用 membership 操作符来检查字典中是否存在该键,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.viewkeys()
print("The keys are:", keys)
input_key = "url"
if input_key in keys:
print("The key '{}' exists in the dictionary.".format(input_key))
else:
print("The key '{}' doesn't exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The keys are:', dict_keys(['url', 'acronym', 'type', 'name']))
The key 'url' exists in the dictionary.
使用 viewkeys()方法检查字典中是否存在多个键
为了使用viewkeys()方法检查字典中是否存在多个键,我们将遍历输入键的列表。
对于每个键,我们将使用成员操作符来检查该键是否存在于由viewkeys()方法返回的dict_keys对象中。如果是,我们将打印出该键存在于字典中。否则,我们将打印出该键不存在。最后,我们将转到下一个键。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.viewkeys()
print("The keys are:", keys)
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for input_key in input_keys:
if input_key in keys:
print("The key '{}' exists in the dictionary.".format(input_key))
else:
print("The key '{}' doesn't exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The keys are:', dict_keys(['url', 'acronym', 'type', 'name']))
('The input keys are:', ['Aditya', 'name', 'url'])
The key 'Aditya' doesn't exist in the dictionary.
The key 'name' exists in the dictionary.
The key 'url' exists in the dictionary.
使用 viewkeys()方法检查字典列表中是否存在某个键
为了使用viewkeys()方法检查一个键是否存在于字典列表中,我们将使用下面的过程。
- 我们将使用 for 循环遍历字典列表。
- 在对字典进行迭代时,我们将首先通过调用字典上的
viewkeys()方法来获得dict_keys对象。之后,我们将使用成员操作符来检查输入键是否出现在dict_keys对象中。 - 如果键存在于
dict_keys对象中,我们将打印出来。之后,我们将使用 break 语句跳出 for 循环。 - 如果我们在当前的
dict_keys对象中没有找到关键字,我们将使用 continue 语句移动到字典列表中的下一个字典。 - 在遍历了所有的字典之后,如果我们没有找到这个键,我们将打印出这个键在字典列表中不存在。
您可以在下面的示例中观察整个过程。
listOfDicts = [{1: 1, 2: 4, 3: 9},
{"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
"type": "python blog"},
{"person": "Aditya", "Country": "India"}
]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
keys = dictionary.viewkeys()
if key in keys:
print("The key '{}' is present in the list of dictionaries.".format(key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' is not present in the list of dictionaries.".format(key))
输出:
('The key is:', 'name')
The key 'name' is present in the list of dictionaries.
使用 iterkeys()方法检查字典中是否存在一个键
在 python 版本中,我们也可以使用iterkeys()方法代替 viewkeys()方法来检查字典中是否存在一个键。
iterkeys()方法
当在 python 字典上调用iterkeys() 方法时,它返回一个迭代器,该迭代器迭代字典的键。
为了使用iterkeys()方法检查一个键是否存在于字典中,我们将首先通过调用字典上的 iterkeys()方法获得迭代器。之后,我们将使用 for 循环和迭代器遍历这些键。
迭代时,我们将检查当前键是否是我们正在搜索的键。如果是,我们会说这个键在字典里。否则不会。您可以在下面的 python 程序中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
iterator = myDict.iterkeys()
input_key = "url"
keyFound = False
for key in iterator:
if key == input_key:
print("The key '{}' exists in the dictionary.".format(input_key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' does not exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The key 'url' exists in the dictionary.
不使用 for 循环,您可以使用成员操作符和 iterkeys()方法来检查字典中是否存在一个键,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
iterator = myDict.iterkeys()
input_key = "url"
if input_key in iterator:
print("The key '{}' exists in the dictionary.".format(input_key))
else:
print("The key '{}' doesn't exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The key 'url' exists in the dictionary.
使用 iterkeys()方法检查字典中是否存在多个键
为了使用iterkeys()方法检查字典中是否存在多个键,我们将首先使用iterkeys()方法获得字典键的迭代器。之后,我们将遍历输入键列表。
对于每个键,我们将使用成员操作符来检查该键是否存在于由iterkeys()方法返回的迭代器对象中。如果是,我们将打印出该键存在于字典中。否则,我们将打印出该键不存在。最后,我们将转到下一个键。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
iterator = myDict.iterkeys()
input_keys = ["Aditya", "name", "url"]
print("The input keys are:", input_keys)
for input_key in input_keys:
if input_key in iterator:
print("The key '{}' exists in the dictionary.".format(input_key))
else:
print("The key '{}' doesn't exist in the dictionary.".format(input_key))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
('The input keys are:', ['Aditya', 'name', 'url'])
The key 'Aditya' doesn't exist in the dictionary.
The key 'name' doesn't exist in the dictionary.
The key 'url' doesn't exist in the dictionary.
使用 iterkeys()方法检查字典列表中是否存在某个键
为了使用iterkeys()方法检查一个键是否存在于字典列表中,我们将使用下面的过程。
- 我们将使用 for 循环遍历字典列表。
- 在对字典进行迭代时,我们将首先通过调用字典上的
iterkeys()方法获得字典键的迭代器。之后,我们将使用成员操作符来检查迭代器中是否存在输入键。 - 如果键出现在迭代器中,我们将打印出来。之后,我们将使用 break 语句跳出 for 循环。
- 如果我们在当前迭代器中没有找到键,我们将使用 python continue 语句移动到字典列表中的下一个字典。
- 在遍历了所有的字典之后,如果我们没有找到这个键,我们将打印出这个键在字典中不存在。
您可以在下面的示例中观察整个过程。
listOfDicts = [{1: 1, 2: 4, 3: 9},
{"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB",
"type": "python blog"},
{"person": "Aditya", "Country": "India"}
]
key = "name"
print("The key is:", key)
keyFound = False
for dictionary in listOfDicts:
iterator = dictionary.iterkeys()
if key in iterator:
print("The key '{}' is present in the list of dictionaries.".format(key))
keyFound = True
break
else:
continue
if not keyFound:
print("The key '{}' is not present in the list of dictionaries.".format(key))
输出:
('The key is:', 'name')
The key 'name' is present in the list of dictionaries.
结论
在本文中,我们讨论了检查一个键是否存在于 python 字典中的不同方法。如果您正在使用 python 3.x,那么在所有方法中,您应该使用使用成员运算符的方法来检查字典中是否存在某个键。如果您正在使用 python 2.x,您可以使用使用iterkeys() 方法的方法来检查给定的键是否存在于字典中。这两种方法对于各自版本的 python 来说是最快的。
我希望你喜欢阅读这篇文章。要了解更多关于 python 编程的知识,您可以阅读这篇关于如何在 Python 中删除列表中所有出现的字符的文章。您可能也喜欢这篇关于如何检查 python 字符串是否包含数字的文章。
请继续关注更多内容丰富的文章。
快乐学习!
检查列表是否有重复的元素
原文:https://www.pythonforbeginners.com/basics/check-if-a-list-has-duplicate-elements
列表是 Python 中最常用的数据结构。在编程时,您可能会遇到这样的情况:您需要一个只包含唯一元素的列表,或者您希望检查一个列表中是否有重复的元素。在本文中,我们将研究不同的方法来检查一个列表中是否有重复的元素。
使用集合检查列表是否有重复的元素
我们知道 Python 中的集合只包含唯一的元素。我们可以使用集合的这个属性来检查一个列表是否有重复的元素。
为此,我们将从列表的元素中创建一个集合。之后,我们将检查列表和集合的大小。如果两个对象的大小相等,它将确认列表中没有重复的元素。如果集合的大小大于列表,这意味着列表包含重复的元素。我们可以从下面的例子中理解这一点。
def check_duplicate(l):
mySet = set(l)
if len(mySet) == len(l):
print("List has no duplicate elements.")
else:
print("The list contains duplicate elements")
list1 = [1, 2, 3, 4, 5, 6, 7]
print("List1 is:", list1)
check_duplicate(list1)
list2 = [1, 2, 1, 2, 4, 6, 7]
print("List2 is:", list2)
check_duplicate(list2)
输出:
List1 is: [1, 2, 3, 4, 5, 6, 7]
List has no duplicate elements.
List2 is: [1, 2, 1, 2, 4, 6, 7]
The list contains duplicate elements
在上面的方法中,我们需要从列表的所有元素中创建一个集合。之后,我们还要检查集合和列表的大小。这些操作非常昂贵。
我们可以只搜索第一个重复的元素,而不是使用这种方法。为此,我们将从列表的第一个元素开始,并不断将它们添加到集合中。在将元素添加到集合之前,我们将检查该元素是否已经存在于集合中。如果是,则列表包含重复的元素。如果我们能够将列表中的每个元素添加到集合中,则列表中不包含任何重复的元素。这可以从下面的例子中理解。
def check_duplicate(l):
visited = set()
has_duplicate = False
for element in l:
if element in visited:
print("The list contains duplicate elements.")
has_duplicate = True
break
else:
visited.add(element)
if not has_duplicate:
print("List has no duplicate elements.")
list1 = [1, 2, 3, 4, 5, 6, 7]
print("List1 is:", list1)
check_duplicate(list1)
list2 = [1, 2, 1, 2, 4, 6, 7]
print("List2 is:", list2)
check_duplicate(list2)
输出:
List1 is: [1, 2, 3, 4, 5, 6, 7]
List has no duplicate elements.
List2 is: [1, 2, 1, 2, 4, 6, 7]
The list contains duplicate elements.
使用 count()方法检查列表中是否有重复的元素
为了检查一个列表是否只有唯一的元素,我们还可以计算列表中不同元素的出现次数。为此,我们将使用 count()方法。在列表上调用 count()方法时,该方法将元素作为输入参数,并返回元素在列表中出现的次数。
为了检查列表是否包含重复的元素,我们将统计每个元素的频率。同时,我们还将维护一个已访问元素的列表,这样我们就不必计算已访问元素的出现次数。一旦发现任何元素的计数大于 1,就证明列表中有重复的元素。我们可以这样实现。
def check_duplicate(l):
visited = set()
has_duplicate = False
for element in l:
if element in visited:
pass
elif l.count(element) == 1:
visited.add(element)
elif l.count(element) > 1:
has_duplicate = True
print("The list contains duplicate elements.")
break
if not has_duplicate:
print("List has no duplicate elements.")
list1 = [1, 2, 3, 4, 5, 6, 7, 8]
print("List1 is:", list1)
check_duplicate(list1)
list2 = [1, 2, 1, 2, 4, 6, 7, 8]
print("List2 is:", list2)
check_duplicate(list2)
输出:
List1 is: [1, 2, 3, 4, 5, 6, 7, 8]
List has no duplicate elements.
List2 is: [1, 2, 1, 2, 4, 6, 7, 8]
The list contains duplicate elements.
使用 counter()方法检查列表中是否有重复的元素
我们还可以使用 counter()方法来检查一个列表是否只有唯一的元素。counter()方法。counter()方法将 iterable 对象作为输入,并返回一个 python 字典,其中键由 iterable 对象的元素组成,与键相关联的值是元素的频率。在使用 counter()方法获得列表中每个元素的频率后,我们可以检查任何元素的频率是否大于 1。如果是,则列表包含重复的元素。否则不会。
from collections import Counter
def check_duplicate(l):
counter = Counter(l)
has_duplicate = False
frequencies = counter.values()
for i in frequencies:
if i > 1:
has_duplicate = True
print("The list contains duplicate elements.")
break
if not has_duplicate:
print("List has no duplicate elements.")
list1 = [1, 2, 3, 4, 5, 6, 7, 8]
print("List1 is:", list1)
check_duplicate(list1)
list2 = [1, 2, 1, 2, 4, 6, 7, 8]
print("List2 is:", list2)
check_duplicate(list2)
输出:
List1 is: [1, 2, 3, 4, 5, 6, 7, 8]
List has no duplicate elements.
List2 is: [1, 2, 1, 2, 4, 6, 7, 8]
The list contains duplicate elements.
结论
在本文中,我们讨论了检查列表是否只有唯一元素的四种方法。我们使用了 sets、count()和 counter()方法来实现我们的方法。要了解更多关于列表的知识,你可以阅读这篇关于列表理解的文章。
检查熊猫系列是否在 Python 中排序
原文:https://www.pythonforbeginners.com/basics/check-if-a-pandas-series-is-sorted-in-python
Pandas 系列是在 python 中处理顺序数据的一个很好的工具。在本文中,我们将讨论检查熊猫系列是否排序的不同方法。
检查熊猫系列是否使用 is_monotonic 属性排序
要检查一个熊猫系列是否按升序排序,我们可以使用该系列的is_monotonic属性。如果熊猫系列按升序排序,则属性is_monotonic的计算结果为 True。
例如,如果一个序列是按升序排序的,那么is_monotonic属性的值将为 True,如下所示。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
输出:
The series is:
2 -100
5 -3
0 3
3 14
4 16
1 23
6 45
7 65
dtype: int64
The series is sorted?:
True
在上面的例子中,我们首先使用Series()构造函数创建了一个系列。然后,我们使用sort_values()方法对序列进行排序。在这之后,我们调用了这个系列的is_monotonic属性。您可以观察到,在按升序排序的序列上调用时,is_monotonic属性的计算结果为 True。
如果序列按降序排序,is_monotonic属性的计算结果将为 False。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
输出:
The series is:
7 65
6 45
1 23
4 16
3 14
0 3
5 -3
2 -100
dtype: int64
The series is sorted?:
False
在这个例子中,我们已经在sort_values()方法中将ascending参数设置为 False。因此,该系列按降序排序。当我们调用按降序排序的序列的is_monotonic属性时,它的计算结果为 False。
如果熊猫系列没有排序,is_monotonic属性将被评估为假。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
输出:
The series is:
0 3
1 23
2 -100
3 14
4 16
5 -3
6 45
7 65
dtype: int64
The series is sorted?:
False
在上面的例子中,我们没有对序列进行排序。因此,is_monotonic属性的计算结果为 False。
is_monotonic属性不适用于 NaN 值。如果一个序列包含 NaN 值,is_monotonic属性的计算结果总是为 False。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
输出:
The series is:
0 3.0
3 14.0
4 16.0
1 23.0
6 45.0
7 65.0
2 NaN
5 NaN
dtype: float64
The series is sorted?:
False
在上面的例子中,我们创建了一个具有 NaN 值的序列。然后,我们按升序对系列进行排序。当对具有 NaN 值的排序序列调用is_monotonic属性时,其计算结果为 False,如输出所示。有人可能会说,排序后的序列中的 NaN 值在底部。这就是为什么is_monotonic属性的计算结果为 False。
然而,即使我们将 NaN 值放在熊猫系列的顶部,is_monotonic属性也将计算为 False,如下所示。
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,na_position="first")
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic)
输出:
The series is:
2 NaN
5 NaN
0 3.0
3 14.0
4 16.0
1 23.0
6 45.0
7 65.0
dtype: float64
The series is sorted?:
False
在上面的示例中,NaN 值出现在排序序列的顶部。即使在这之后,is_monotonic属性的计算结果也是 False。
使用is_monotonic属性时,您将得到一个 FutureWarning,并显示消息“ FutureWarning: is_monotonic 已被否决,将在未来版本中删除。请改用 is_monotonic_increasing。”这意味着is_monotonic属性将在未来的 pandas 版本中被弃用。作为替代,我们可以使用is_monotonic_increasing和is_monotonic_decreasing属性来检查熊猫系列在 python 中是否排序。
检查熊猫系列是否按升序排序
要检查熊猫系列是否按升序排序,我们可以使用is_monotonic_increasing属性。如果序列按升序排序,则is_monotonic_increasing属性的计算结果为 True。否则,它被设置为 False。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
输出:
The series is:
2 -100
5 -3
0 3
3 14
4 16
1 23
6 45
7 65
dtype: int64
The series is sorted?:
True
在上面的例子中,我们使用了is_monotonic_increasing属性来检查序列是否被排序。因为我们已经按升序对系列进行了排序,所以is_monotonic_increasing属性的计算结果为 True。
如果序列没有按升序排序,则is_monotonic_increasing属性的计算结果为 False。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
输出:
The series is:
0 3
1 23
2 -100
3 14
4 16
5 -3
6 45
7 65
dtype: int64
The series is sorted?:
False
在上面的例子中,我们没有对输入序列进行排序。因此,当在 series 对象上调用时,is_monotonic_increasing属性的计算结果为 False。
此外,如果熊猫系列按降序排序,is_monotonic_increasing属性的计算结果为 False。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
输出:
The series is:
7 65
6 45
1 23
4 16
3 14
0 3
5 -3
2 -100
dtype: int64
The series is sorted?:
False
在本示例中,系列按降序排序。因此,is_monotonic_increasing属性的计算结果为 False。
is_monotonic_increasing不能用于具有 NaN 值的系列对象。如果 pandas 系列有 NaN 值,则is_monotonic_increasing属性总是计算为 False。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
输出:
The series is:
0 3.0
3 14.0
4 16.0
1 23.0
6 45.0
7 65.0
2 NaN
5 NaN
dtype: float64
The series is sorted?:
False
在上面的例子中,我们创建了一个具有 NaN 值的序列。然后,我们按升序对系列进行排序。当对具有 NaN 值的排序序列调用is_monotonic_increasing属性时,其计算结果为 False,如输出所示。有人可能会说,排序后的序列中的 NaN 值在底部。这就是为什么is_monotonic_increasing属性的计算结果为 False。
即使我们将 NaN 值放在序列的顶部,is_monotonic_increasing属性也将计算为 False。
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,na_position="first")
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_increasing)
输出:
The series is:
2 NaN
5 NaN
0 3.0
3 14.0
4 16.0
1 23.0
6 45.0
7 65.0
dtype: float64
The series is sorted?:
False
在本例中,NaN 值放在排序序列的顶部。即使在这之后,is_monotonic_increasing属性的计算结果也是 False。它显示了is_monotonic_increasing属性不支持 NaN 值。
有趣的阅读:Python 中的命令行参数
检查一个系列在 Python 中是否按降序排序
为了检查熊猫系列是否按降序排序,我们将使用is_monotonic_decreasing属性。如果序列按降序排序,则is_monotonic_decreasing属性的计算结果为 True。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_decreasing)
输出:
The series is:
7 65
6 45
1 23
4 16
3 14
0 3
5 -3
2 -100
dtype: int64
The series is sorted?:
True
在上面的例子中,我们使用了is_monotonic_decreasing属性来检查序列是否按降序排序。因为我们已经按升序对系列进行了排序,所以is_monotonic_decreasing属性的计算结果为 True。
如果序列未排序或按升序排序,则is_monotonic_decreasing属性的计算结果为 False,如下所示。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_decreasing)
输出:
The series is:
0 3
1 23
2 -100
3 14
4 16
5 -3
6 45
7 65
dtype: int64
The series is sorted?:
False
在上面的例子中,is_monotonic_decreasing属性是在一个未排序的序列上调用的。因此,它的计算结果为假。
is_monotonic_decreasing属性不能用于具有 NaN 值的系列对象。如果 pandas 系列有 NaN 值,则is_monotonic_decreasing属性总是计算为 False。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False)
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_decreasing)
输出:
The series is:
7 65.0
6 45.0
1 23.0
4 16.0
3 14.0
0 3.0
2 NaN
5 NaN
dtype: float64
The series is sorted?:
False
在上面的例子中,我们创建了一个具有 NaN 值的序列。然后,我们按降序对系列进行排序。当对具有 NaN 值的排序序列调用is_monotonic_decreasing属性时,其计算结果为 False,如输出所示。有人可能会说,排序后的序列中的 NaN 值在底部。这就是为什么is_monotonic_decreasing属性的计算结果为 False。
然而,即使我们将 NaN 值放在序列的顶部,is_monotonic_decreasing属性也将计算为 False。
import pandas as pd
import numpy as np
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(numbers)
series.sort_values(inplace=True,ascending=False,na_position="first")
print("The series is:")
print(series)
print("The series is sorted?:")
print(series.is_monotonic_decreasing)
输出:
The series is:
2 NaN
5 NaN
7 65.0
6 45.0
1 23.0
4 16.0
3 14.0
0 3.0
dtype: float64
The series is sorted?:
False
在本例中,我们将 NaN 值放在排序序列的顶部。即使在这之后,is_monotonic_decreasing属性的计算结果也是 False。这证实了我们可以将is_monotonic_decreasing用于具有 NaN 值的序列。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇 MLFlow 教程,里面有代码示例。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
检查序列是否使用 Numpy 模块排序
python 中的 numpy 模块为我们提供了不同的函数来对数值数据执行操作。一个这样的函数是diff() 函数。diff() 函数将一个像 series 这样的可迭代对象作为其输入参数,并返回一个包含数组元素的一阶差的数组,如下例所示。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
print("The series is:")
print(series)
temp=np.diff(series)
print("Array returned by diff() is:")
print(temp)
输出:
The series is:
0 3
1 23
2 -100
3 14
4 16
5 -3
6 45
7 65
dtype: int64
Array returned by diff() is:
[ 20 -123 114 2 -19 48 20]
在上面的例子中,我们已经将序列传递给了diff()函数。您可以观察到列表中的元素是系列中元素的差异。例如,输出列表中的第一个元素是序列中第二个和第一个元素之间的差。类似地,输出列表中的第二个元素是序列的第三和第二个元素之间的差。
因此,您可以观察到,一阶差被计算为输入序列中第(n+1)个和第 n 个元素之间的差。
为了检查熊猫系列是否使用diff()函数按升序排序,我们将使用以下步骤。
- 首先我们来计算熊猫系列的一阶差分。为此,我们将把序列作为输入参数传递给
diff()函数。 - 之后,我们将检查输出数组中的所有元素是否都大于或等于 0。为此,我们将使用比较运算符和
all()方法。当我们在 numpy 数组上使用比较运算符时,我们会得到一个布尔值数组。在包含布尔值的数组上调用all()方法时,如果所有元素都为真,则返回真。 - 如果
all()方法返回 True,它将得出熊猫系列按升序排序的结论。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series=series.sort_values()
print("The series is:")
print(series)
temp=np.diff(series)
boolean_array= temp>=0
print("Boolean array is:")
print(boolean_array)
result=boolean_array.all()
if result:
print("The series is sorted.")
else:
print("The series is not sorted.")
输出:
The series is:
2 -100
5 -3
0 3
3 14
4 16
1 23
6 45
7 65
dtype: int64
Boolean array is:
[ True True True True True True True]
The series is sorted.
为了检查熊猫系列是否按降序排序,我们将检查diff()函数的输出数组中的所有元素是否都小于或等于 0。为此,我们将使用比较运算符和all()方法。当我们在 numpy 数组上使用比较运算符时,我们会得到一个布尔值数组。在包含布尔值的数组上调用all()方法时,如果所有元素都为真,则返回真。
如果all()方法返回 True,它将得出熊猫系列按降序排序的结论。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(numbers)
series=series.sort_values(ascending=False)
print("The series is:")
print(series)
temp=np.diff(series)
boolean_array= temp<=0
print("Boolean array is:")
print(boolean_array)
result=boolean_array.all()
if result:
print("The series is sorted.")
else:
print("The series is not sorted.")
输出:
The series is:
7 65
6 45
1 23
4 16
3 14
0 3
5 -3
2 -100
dtype: int64
Boolean array is:
[ True True True True True True True]
The series is sorted.
检查 Python 中序列的索引是否排序
要检查熊猫系列的索引是否排序,我们可以使用如下所示的index属性和is_monotonic属性。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
sorted_series=series.sort_index()
print("The series is:")
print(sorted_series)
print("The index of series is sorted?:")
print(sorted_series.index.is_monotonic)
输出:
The series is:
2 abcd
3 a
11 c
14 ab
16 abc
23 b
45 bc
65 d
dtype: object
The index of series is sorted?:
True
要检查熊猫系列的索引是否按升序排序,我们可以使用如下所示的index属性和is_monotonic_increasing属性。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
sorted_series=series.sort_index()
print("The series is:")
print(sorted_series)
print("The index of series is sorted?:")
print(sorted_series.index.is_monotonic_increasing)
输出:
The series is:
2 abcd
3 a
11 c
14 ab
16 abc
23 b
45 bc
65 d
dtype: object
The index of series is sorted?:
True
要检查熊猫系列的索引是否按降序排序,我们可以使用如下所示的index属性和is_monotonic_decreasing属性。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
sorted_series=series.sort_index(ascending=False)
print("The series is:")
print(sorted_series)
print("The index of series is sorted?:")
print(sorted_series.index.is_monotonic_decreasing)
输出:
The series is:
65 d
45 bc
23 b
16 abc
14 ab
11 c
3 a
2 abcd
dtype: object
The index of series is sorted?:
True
您需要记住,如果索引列包含 NaN 值,那么is_monotonic属性、is_monotonic_increasing属性和is_monotonic_decreasing总是返回 False。因此,如果索引列包含 NaN 值,则不能使用这些属性来检查索引是否已排序。
结论
在本文中,我们讨论了检查熊猫系列是否排序的不同方法。要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
检查 Python 字符串是否包含数字
原文:https://www.pythonforbeginners.com/strings/check-if-a-python-string-contains-a-number
在 python 编程语言中,字符串用于处理文本数据。有时,在我们必须验证用户输入或数据的情况下,我们需要检查字符串是否包含数字。在本 python 教程中,我们将讨论检查给定字符串是否包含数字的不同方法。
使用 order()函数检查 Python 字符串是否包含数字
在 ASCII 编码中,数字用于表示字符。每个字符都被分配了一个 0 到 127 之间的特定数字。我们可以使用ord()函数在 python 中找到任意数字的 ASCII 值。
order()函数将一个字符作为其输入参数,并返回其 ASCII 值。您可以在下面的 python 代码中观察到这一点。
zero = "0"
nine = "9"
print("The ASCII value of the character \"0\" is:", ord(zero))
print("The ASCII value of the character \"9\" is:", ord(nine))
输出:
The ASCII value of the character "0" is: 48
The ASCII value of the character "9" is: 57
正如您在上面的 python 程序中看到的,字符“0”的 ASCII 值是 48。此外,字符“9”的 ASCII 值是 57。因此,任何数字字符的 ASCII 值都在 48 到 57 之间。
在 python 中,我们可以使用数字字符的 ASCII 值来检查字符串是否包含数字。为此,我们将字符串视为一个字符序列。
之后,我们将遵循下面提到的步骤。
- 我们将使用一个 for 循环和一个
flag变量遍历原始字符串对象的字符。最初,我们将把变量flag初始化为布尔值False。 - 之后,我们将遍历给定输入字符串的字符。迭代时,我们将把每个字符转换成它的 ASCII 数值。
- 之后,我们将检查数值是否在 48 和 57 之间。如果是,字符代表一个数字,因此我们可以说字符串包含一个整数值。
- 一旦我们找到一个字符,它的 ASCII 值在 48 到 57 之间,我们将把布尔值
True赋给flag变量,表明该字符串包含数字字符。在这里,我们已经发现字符串包含一个数字。因此,我们将使用中断语句退出 for 循环。 - 如果我们在执行 for 循环时没有找到代表一个数字的字符,
flag变量将包含值False。
在 for 循环执行之后,我们将检查flag变量是否包含值True。如果是,我们将打印该字符串包含一个数字。否则,我们将打印字符串不包含任何数字。您可以在下面的代码中观察到这一点。
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
ascii_val = ord(character)
if 48 <= ascii_val <= 57:
flag = True
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
如果您以一个空字符串作为输入来运行上例中给出的代码,程序将按预期运行。因此,在执行 for 循环之前,将变量flag初始化为False非常重要。否则,程序将无法正常工作。
使用 isnumeric()方法检查 Python 字符串是否为数字
Python 为我们提供了不同的字符串方法,用它们我们可以检查一个字符串是否包含数字。当在字符串上调用isnumeric()方法时,如果字符串仅由数字字符组成,则返回True。如果字符串包含非数字字符,则返回False。
我们可以使用如下例所示的isnumeric()方法检查一个字符串是否只包含数字字符。
myStr1 = "123"
isNumber = myStr1.isnumeric()
print("{} is a number? {}".format(myStr1, isNumber))
myStr2 = "PFB"
isNumber = myStr2.isnumeric()
print("{} is a number? {}".format(myStr2, isNumber))
输出:
123 is a number? True
PFB is a number? False
如果我们得到一个包含字母数字字符的字符串,您也可以使用isnumeric() 方法检查该字符串是否包含数字。为此,我们将使用 For 循环遍历原始字符串对象的字符。
- 迭代时,我们将对每个字符调用
isnumeric()方法。如果字符代表一个数字,isnumeric()方法将返回True。因此,我们可以说字符串包含一个数字。 - 我们将把由
isnumeric()方法返回的布尔值赋给flag变量。 - 如果
flag变量的值为True,则表明该字符串包含数字字符。一旦我们发现字符串包含一个数字,我们将使用 break 语句退出 for 循环。 - 如果我们在执行 for 循环时没有找到代表一个数字的字符,
flag变量将包含值False。
如果在 for 循环执行之后,flag变量包含值False,我们就说这个字符串包含数字。否则,我们会说字符串不包含数字。您可以在下面的代码中观察到这一点。
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
flag = character.isnumeric()
if flag:
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
使用 isdigit()方法验证 Python 字符串是否包含数字
我们可以使用isdigit()方法来检查一个字符串是否是数字,而不是上一节中使用的isnumeric()。在字符串上调用isdigit()方法时,如果字符串中的所有字符都是十进制数字,则返回True。否则,它返回False。您可以在下面的示例中观察到这一点。
myStr1 = "1"
isDigit = myStr1.isdigit()
print("{} is a digit? {}".format(myStr1, isDigit))
myStr2 = "A"
isDigit = myStr2.isnumeric()
print("{} is a digit? {}".format(myStr2, isDigit))
输出:
1 is a digit? True
A is a digit? False
我们还可以使用 isdigit()方法检查一个字符串是否包含数字。为此,我们将使用 For 循环遍历原始字符串对象的字符。
- 迭代时,我们将对每个字符调用
isdigit()方法。如果字符代表一个数字,isdigit()方法将返回True。因此,我们可以说字符串包含一个数字。 - 我们将把由
isdigit()方法返回的布尔值赋给flag变量。如果flag变量的值为True,则表明该字符串包含数字字符。 - 一旦我们发现字符串包含一个数字,我们将使用 break 语句退出 for 循环。
- 如果我们在执行 for 循环时没有找到代表一个数字的字符,
flag变量将包含值False。
如果在 for 循环执行之后,flag变量包含值False,我们就说这个字符串包含数字。否则,我们会说字符串不包含数字。
您可以在下面的代码中观察到这一点。
myStr = "I am 23 but it feels like I am 15."
flag = False
for character in myStr:
flag = character.isdigit()
if flag:
break
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
使用 map()和 any()函数检查 Python 字符串是否包含数字
在前面的章节中,我们使用了各种方法来检查 python 字符串是否包含数字。为此,我们在每个示例中使用 For 循环遍历了输入字符串。然而,我们也可以在不显式迭代字符串的情况下检查字符串是否包含数字。为此,我们将使用map()函数。
map()函数将一个函数作为它的第一个输入参数,比如说func,将一个可迭代对象比如说iter作为它的第二个输入参数。执行时,它执行第一个输入参数中给出的函数func,并将iter的元素作为func的输入参数。执行后,它返回一个 map 对象,该对象包含当它以iter的元素作为输入参数执行时由func返回的值。
您可以使用list()构造函数将地图对象转换成列表。
例如,看看下面的源代码。
from math import sqrt
numbers = [1, 4, 9, 16, 25]
print("The numbers are:", numbers)
square_roots = list(map(sqrt, numbers))
print("The square roots are:", square_roots)
输出:
The numbers are: [1, 4, 9, 16, 25]
The square roots are: [1.0, 2.0, 3.0, 4.0, 5.0]
在上面的代码中,我们将sqrt()函数作为第一个输入参数,将一个包含正数的列表作为map()函数的第二个参数。执行后,我们获得了一个包含输入列表元素平方根的列表。
为了使用map()函数检查 python 字符串是否包含数字,我们将创建一个函数myFunc。函数myFunc应该将一个字符作为它的输入参数。执行后,如果字符是数字,它应该返回True。否则,它应该返回False。
在myFunc里面,我们可以用isdigit()的方法来检查输入的字符是否是数字。
我们将把myFunc()函数作为第一个参数,把输入字符串作为第二个输入参数传递给map() 方法。执行后,map()函数将返回一个地图对象。
当我们将 map 对象转换成一个列表时,我们会得到一个布尔值列表True和False。列表中值的总数将等于输入字符串中的字符数。此外,每个布尔值对应于字符串中相同位置的一个字符。换句话说,列表的第一个元素对应于输入字符串中的第一个字符,列表的第二个元素对应于输入字符串中的第二个字符,依此类推。
如果字符串中有任何数字字符,输出列表中对应的元素将是True。因此,如果从 map 对象获得的列表在其至少一个元素中包含值True,我们将得出输入字符串包含数字的结论。
为了确定输出列表是否包含值True作为其元素,我们将使用any()函数。
any()函数将列表作为其输入参数,如果至少有一个值是True,则返回True。否则返回False。
因此,如果any()函数在执行后返回True,我们将说输入字符串包含一个数字。否则,我们将断定输入字符串不包含数字字符。
您可以在下面的代码中观察到这一点。
def myFunc(character):
return character.isdigit()
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(myFunc, myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
这种方法也适用于较大的字符串,因为我们不需要逐个字符地遍历输入字符串。
除了定义 myFunc,还可以将一个 lambda 函数传递给 map()函数。这将使你的代码更加简洁。
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(lambda character: character.isdigit(), myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
除了使用isdigit()方法,还可以使用 isnumeric()方法以及map()函数和any() 函数来检查 python 字符串是否包含数字,如下例所示。
def myFunc(character):
return character.isnumeric()
myStr = "I am 23 but it feels like I am 15."
flag = any(list(map(myFunc, myStr)))
print("The string is:")
print(myStr)
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
前面讨论的所有方法都使用标准的字符串方法和字符串值。然而,python 也为我们提供了正则表达式模块‘re’来处理文本数据和字符串。
现在让我们讨论如何使用正则表达式检查 python 字符串是否包含数字。
使用正则表达式检查 Python 字符串是否包含数字
正则表达式用于在 python 中操作文本数据。我们还可以使用正则表达式来检查 python 字符串是否包含数字。为此,我们可以使用match()方法和search()方法。让我们逐一讨论这两种方法。
使用 match()方法验证 Python 字符串是否包含数字
match()方法用于查找特定模式在字符串中第一次出现的位置。它将正则表达式模式作为第一个参数,将输入字符串作为第二个参数。如果存在与正则表达式模式匹配的字符串字符序列,它将返回一个 match 对象。否则,它返回 None。
要使用match()方法检查字符串是否包含数字,我们将遵循以下步骤。
- 首先,我们将定义数字的正则表达式模式。因为数字是一个或多个数字字符的序列,所以数字的正则表达式模式是
“\d+”。 - 定义模式后,我们将把模式和输入字符串传递给
match()方法。 - 如果
match()方法返回None,我们就说这个字符串不包含任何数字。否则,我们会说字符串包含数字。
您可以在下面的示例中观察到这一点。
import re
myStr = "23 but it feels like I am 15."
match_object = re.match(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
输出:
The string is:
23 but it feels like I am 15.
String contains numbers?: True
只有当数字出现在字符串的开头时, match() 方法才有效。在其他情况下,它无法检查给定的字符串是否包含数字。您可以在下面的示例中观察到这一点。
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.match(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: False
在上面的例子中,您可以看到字符串包含数字。然而,程序断定字符串中没有任何数字。为了避免在检查字符串中的数字时出错,我们可以使用search()方法来代替match()方法。
使用 search()方法检查 Python 字符串是否包含数字
search()方法用于查找字符串中特定模式的位置。它将正则表达式模式作为第一个参数,将输入字符串作为第二个参数。如果存在与正则表达式模式匹配的字符串字符序列,它将返回一个 match 对象,该对象包含该模式第一次出现的位置。否则返回None。
为了使用search()方法检查一个字符串是否包含一个数字,我们将遵循使用match()方法的所有步骤。唯一的区别是我们将使用search()方法而不是match()方法。您可以在下面的示例中观察到这一点。
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.search(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
search()方法在整个字符串中搜索。执行后,它返回一个匹配对象,该对象包含输入模式的第一个匹配项。因此,即使字符串中只有一个数字,search()方法也会找到它。然而,这并不适用于match()方法。
使用 findall()方法检查 Python 字符串是否包含数字
findall()方法在语义上类似于 search()方法。不同之处在于findall()方法返回模式的所有出现,而不是模式的第一次出现。当输入字符串中不存在模式时,findall()方法返回None。
您可以使用如下所示的findall()方法检查 python 字符串是否包含数字。
import re
myStr = "I am 23 but it feels like I am 15."
match_object = re.findall(r"\d+", myStr)
print("The string is:")
print(myStr)
flag = False
if match_object:
flag = True
print("String contains numbers?:", flag)
输出:
The string is:
I am 23 but it feels like I am 15.
String contains numbers?: True
结论
在本文中,我们讨论了检查 python 字符串是否包含数字的不同方法。在所有这些方法中,使用正则表达式的方法是最有效的。如果我们讨论编写更多 pythonic 代码,您可以使用map()函数和any()函数来检查字符串是否包含数字。与字符串方法相比,正则表达式是更好的选择。因此,为了获得最佳的执行时间,您可以使用re.search()方法来检查一个字符串是否包含数字。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中检查字符串是否为空或空白
原文:https://www.pythonforbeginners.com/basics/check-if-a-string-is-empty-or-whitespace-in-python
Python 中的字符串用于处理文本数据。在对文本数据进行操作时,我们可能需要删除空字符串或空白。当我们打印空字符串或空白时,我们无法区分这两者。在本文中,我们将讨论 Python 中检查字符串是否为空或空白的不同方法。这将帮助您区分空字符串和空白。
使用等式运算符检查 Python 中的字符串是否为空或空白
要使用等号运算符检查一个字符串是否为空,我们只需将该字符串与另一个空字符串进行比较。如果结果为真,则输入字符串为空。否则不会。
input_string=""
print("The input string is:",input_string)
if input_string=="":
print("Input string is an empty string.")
输出:
The input string is:
Input string is an empty string.
要检查字符串是否只包含空白字符,可以将其与空字符串进行比较。如果结果为 False,字符串将包含空白字符。您可以在下面的示例中观察到这一点。
input_string=" "
print("The input string is:",input_string)
if input_string=="":
print("Input string is an empty string.")
else:
print("Input string is a whitespace character.")
输出:
The input string is:
Input string is a whitespace character.
这里,包含空格以外的字符的输入字符串也将返回 False,如下所示。
input_string="Aditya"
print("The input string is:",input_string)
if input_string=="":
print("Input string is an empty string.")
else:
print("Input string is a whitespace character.")
输出:
The input string is: Aditya
Input string is a whitespace character.
在上面的例子中,你可以看到我们使用了字符串“Aditya”。然而,程序告诉我们字符串只包含空格。因此,该程序在逻辑上是不正确的。因此,只有当您确定输入字符串要么是空字符串,要么只包含空白字符时,才可以使用这种方法。
在 Python 中使用 len()函数检查字符串是否为空或空白
len()函数用于查找列表、字符串、元组等可迭代对象的长度。它将 iterable 对象作为其输入参数,并返回 iterable 对象的长度。
要使用 Python 中的 len() 函数检查字符串是空的还是空白,我们将使用以下步骤。
- 首先,我们将使用
len()函数找到输入字符串的长度。我们将把长度存储在变量str_len中。 - 现在,我们将检查输入字符串的长度是否为 0。
- 如果输入字符串的长度为 0,我们就说该字符串是空字符串。否则,我们会说字符串包含空白。
您可以在下面的示例中观察到这一点。
input_string=""
print("The input string is:",input_string)
str_len=len(input_string)
if str_len==0:
print("Input string is an empty string.")
else:
print("Input string is a whitespace character.")
输出:
The input string is:
Input string is an empty string.
同样,如果输入字符串包含空格以外的字符,程序将给出错误的结果,如下所示。
input_string = "Aditya"
print("The input string is:", input_string)
str_len = len(input_string)
if str_len == 0:
print("Input string is an empty string.")
else:
print("Input string is a whitespace character.")
输出:
The input string is: Aditya
Input string is a whitespace character.
同样,你可以看到我们使用了字符串 “Aditya”。然而,程序告诉我们字符串只包含空格。因此,该程序在逻辑上是不正确的。因此,只有当您确定输入字符串要么是空字符串,要么只包含空白字符时,才可以使用这种方法。
在 Python 中使用 not 运算符查找字符串是否为空或空白
在 Python 中,我们还可以使用 not 操作符来检查字符串是空的还是空白。
在 Python 中,所有的可迭代对象,如字符串、列表和元组,当它们为空时,计算结果为 False。因此,空字符串的计算结果为 False。
为了使用 not 操作符检查一个字符串是空的还是空白的,我们将在输入字符串上使用 not 操作符。如果字符串为空,字符串将计算为 False。然后,not 运算符将结果转换为 True。
因此,如果输出为真,我们会说字符串是空的。否则,我们会说字符串包含空白。您可以在下面的示例中观察到这一点。
input_string = ""
print("The input string is:", input_string)
if not input_string:
print("Input string is an empty string.")
else:
print("Input string is a whitespace character.")
输出:
The input string is:
Input string is an empty string.
同样,如果输入字符串包含空格以外的字符,程序会说该字符串只包含空格。因此,只有当您确定输入字符串要么是空字符串,要么只包含空白字符时,才可以使用这种方法。
在 Python 中使用 For 循环检查字符串是否为空或空白
python 中有六个空白字符,分别是空格“ ”,制表符 “\t”,换行符“\n”,竖线制表符”\v”,回车符“\r”,以及 “\f”回车符。我们可以使用这些空白字符的列表和 for 循环来检查一个字符串是空的还是 python 中的空白。为此,我们将使用以下步骤。
- 首先,我们将定义一个名为
whitespaces的列表来存储空白字符。 - 然后,我们将定义一个变量
isWhiteSpace,并将其初始化为 True。 - 现在,我们将使用等式运算符检查输入字符串是否为空字符串。
- 如果输入字符串是一个空字符串,我们将这样打印。
- 如果输入字符串不为空,我们将使用 for 循环迭代输入字符串的字符。
- 在 for 循环中,我们将使用成员操作符和
whitespaces列表检查当前字符是否是空白字符。 - 如果当前字符不是空白字符,我们将赋值 False 给变量
isWhiteSpace。然后,我们将使用中断语句来中断 for 循环。 - 在 for 循环之外,如果
isWhiteSpace为真,我们将打印出该字符串只包含空白字符。 - 否则,我们将打印出字符串包含空格以外的字符。
您可以在下面的示例中观察整个过程。
input_string = " "
whitespaces = [" ", "\t", "\n", "\v", "\r", "\f"]
print("The input string is:", input_string)
isWhiteSpace = True
if input_string == "":
print("Input string is an empty string.")
else:
for character in input_string:
if character in whitespaces:
continue
else:
isWhiteSpace = False
break
if isWhiteSpace:
print("The string contains only whitespace characters.")
else:
print("The string contains characters other than whitespaces.")
输出:
The input string is:
The string contains only whitespace characters.
在 Python 中使用列表理解来发现一个字符串是空的还是空白
列表理解用于从现有的可迭代对象创建一个列表。然而,我们可以使用all() 函数和 list comprehension 来检查 Python 中的输入字符串是否为空或空白。
all() 函数将一个 iterable 对象作为它的输入参数。如果 iterable 对象的所有元素都计算为 True,则返回 True。否则,它返回 False。
为了使用 Python 中的列表理解来检查字符串是空的还是空白的,我们将使用以下步骤。
- 首先,我们将定义一个名为
whitespaces的列表来存储空白字符。 - 然后,我们将使用等式运算符检查输入字符串是否为空字符串。
- 如果输入字符串是一个空字符串,我们将这样打印。
- 如果输入字符串不为空,我们将使用列表理解创建一个布尔值列表。
- 在列表理解中,如果输入字符串中的字符是空白字符,我们将在输出列表中包含 True。否则,我们将在输出列表中包含 False。
- 创建布尔值列表后,我们将把它传递给
all()函数。如果all()函数返回 True,这意味着字符串只包含空白字符。因此,我们将打印相同的内容。 - 如果 all()函数返回 False,我们将打印出输入字符串包含空白字符以外的字符。
您可以在下面的示例中观察整个过程。
input_string = " "
whitespaces = [" ", "\t", "\n", "\v", "\r", "\f"]
print("The input string is:", input_string)
if input_string == "":
print("Input string is an empty string.")
else:
myList = [True for character in input_string if character in whitespaces]
output = all(myList)
if output:
print("The string contains only whitespace characters.")
else:
print("The string contains characters other than whitespaces.")
输出:
The input string is:
The string contains only whitespace characters.
使用 strip()方法检查 Python 中的字符串是否为空或空白
strip()方法用于删除字符串中的前导或尾随空格。当invoked() 在字符串上时,从字符串中删除前导和尾随空格。执行后,它返回修改后的字符串。
为了检查 Python 中的字符串是空的还是空白,我们将使用以下步骤。
- 首先,我们将使用等式运算符检查字符串是否为空。
- 如果字符串为空,我们将这样打印。否则,我们将在字符串上调用
strip()方法。 - 如果
strip()方法返回一个空字符串,我们可以说原始字符串只包含空白字符。因此,我们将这样打印。 - 如果
strip()方法返回非空字符串,则输入字符串包含除空白字符以外的字符。因此,我们将打印该字符串包含除空白字符以外的字符。
您可以在下面的示例中观察整个过程。
input_string = " . "
print("The input string is:", input_string)
if input_string == "":
print("Input string is an empty string.")
else:
newStr = input_string.strip()
if newStr == "":
print("The string contains only whitespace characters.")
else:
print("The string contains characters other than whitespaces.")
输出:
The input string is: .
The string contains characters other than whitespaces.
这种方法甚至适用于包含空格以外的字符的字符串。因此,你可以在任何情况下使用这种方法。
使用 isspace()方法检查 Python 中的字符串是否为空或空白
方法用来检查一个字符串是否只包含空白字符。在字符串上调用时,如果字符串只包含空白字符,则isspace()方法返回 True。否则,它返回 False。
为了使用isspace()方法在 Python 中检查一个字符串是空的还是空白,我们将使用以下步骤。
- 首先,我们将使用等式运算符检查字符串是否为空。
- 如果字符串为空,我们将这样打印。否则,我们将在字符串上调用
isspace()方法。 - 如果
isspace()方法返回 True,这意味着输入字符串只包含空白字符。 - 如果
isspace()方法返回 False,则输入字符串包含空白字符以外的字符。因此,我们将打印该字符串包含除空白字符以外的字符。
您可以在下面的示例中观察到这一点。
input_string = " A "
print("The input string is:", input_string)
if input_string == "":
print("Input string is an empty string.")
elif input_string.isspace():
print("The string contains only whitespace characters.")
else:
print("The string contains characters other than whitespaces.")
输出:
The input string is: A
The string contains characters other than whitespaces.
同样,这种方法甚至适用于包含非空白字符的字符串。因此,你可以在任何情况下使用这种方法。
使用正则表达式检查 Python 中的字符串是否为空或空白
正则表达式用于在 python 中高效地操作字符串。我们还可以使用正则表达式来检查给定的字符串是空的还是空白。为此,我们将使用search()函数。
search()函数将一个字符串模式作为它的第一个输入参数,将一个字符串作为它的第二个输入参数。执行后,它返回一个匹配对象。如果作为第二个输入参数给定的输入字符串中的子字符串与作为第一个输入参数给定的模式相匹配,那么 match 对象不是 None。如果字符串中不存在该模式,匹配对象将为 None。
要使用search()函数检查给定的字符串是空的还是空白字符,我们将使用以下步骤。
- 首先,我们将使用等式运算符检查字符串是否为空。
- 如果字符串为空,我们将这样打印。否则,我们将使用
search()函数来检查字符串是否只包含空白字符。 - 因为我们需要检查字符串是否只包含空格,所以我们将检查字符串中是否有任何非空格字符。为此,我们将把模式
“\S”作为第一个输入参数传递给search()函数。此外,我们将把输入字符串作为第二个输入参数传递给search()函数。 - 如果
search()函数返回 None,则意味着字符串中没有非空白字符。因此,我们将打印出该字符串只包含空白字符。 - 如果
search()函数返回一个匹配对象,我们就说这个字符串包含了除空白字符以外的字符。
您可以在下面的示例中观察到这一点。
from re import search
input_string = " "
pattern = "\\S"
print("The input string is:", input_string)
if input_string == "":
print("Input string is an empty string.")
else:
match_object = search(pattern, input_string)
if match_object is None:
print("The string contains only whitespace characters.")
else:
print("The string contains characters other than whitespaces.")
输出:
The input string is:
The string contains only whitespace characters.
结论
在本文中,我们讨论了在 Python 中检查字符串是否为空或空白的不同方法。在所有三种方法中,使用等式运算符而不是运算符的方法以及len()函数在逻辑上是不正确的。只有当我们确定输入字符串要么是空字符串,要么只包含空白字符时,才能使用它们。
使用strip() 方法、isspace()方法和re.search() 函数的方法是稳健的。这些方法可以在所有情况下使用。因此,我建议您使用这些方法来检查 Python 中给定的字符串是空的还是空白。
要了解更多关于编程的知识,你可以阅读这篇关于数据建模工具的文章。你可能也会喜欢这篇关于机器学习中回归的文章。你也可以看看这篇关于数据分析师和数据科学家的文章,文章比较了数据分析师和数据科学家的工资、教育和工作职责。
检查 Python 中的字典中是否存在值
原文:https://www.pythonforbeginners.com/basics/check-if-value-exists-in-a-dictionary-in-python
我们使用字典来存储和操作 python 程序中的键值对。有时,我们需要检查一个值是否存在于字典中。在本 python 教程中,我们将讨论检查一个值是否存在于 python 字典中的不同方法。在这里,当检查值时,我们可能有可用的键。我们将讨论在这两种情况下如何检查一个值是否存在于字典中。
当我们有可用的键时,检查字典中是否存在一个值
当我们有了字典的键时,我们可以使用下标操作符或get()方法来检查字典中是否存在给定的值。让我们逐一讨论每种方法。
使用下标运算符检查字典中是否存在某个值
下标运算符
当我们有一个键,我们想检查一个值是否存在于字典中,我们可以使用下标操作符。为此,我们可以使用方括号来检索与使用以下语法的键相关联的值。
value=dict[key_val]
这里,dict是字典的名称,key_val是键。执行后,上述语句返回与字典中的键相关联的值。您可以在下面的代码示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
value = myDict[key]
print("The value associated with the key \"{}\" is \"{}\".".format(key, value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The value associated with the key "name" is "Python For Beginners".
这里,我们首先创建了一个字典名myDict,带有关键字name、url、acronym和type。之后,我们使用下标操作符检索了与键'name'相关联的值。在这里,程序正常工作。
但是,可能会出现字典中不存在提供给下标操作符的键的情况。在这种情况下,程序会遇到如下所示的KeyError异常。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "class"
value = myDict[key]
print("The value associated with the key \"{}\" is \"{}\".".format(key, value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 5, in <module>
value = myDict[key]
KeyError: 'class'
这里,关键字'class'在字典中不存在。因此,程序运行到[KeyError](https://www.pythonforbeginners.com/basics/python-keyerror)异常。
在这种情况下,程序会突然终止,程序执行期间所做的任何工作都会丢失。在这些情况下,您可以使用 python try-except 块来处理异常,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "class"
try:
value = myDict[key]
print("The value associated with the key \"{}\" is \"{}\".".format(key, value))
except KeyError:
print("The key '{}' is not present in the dictionary.".format(key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The key 'class' is not present in the dictionary.
在上面的例子中,KeyError异常是在 try 块中引发的。在 except 块中,我们捕获异常,并通过为用户打印适当的消息来正常终止程序。
当我们只有一个输入键时
为了使用下标符号检查一个值是否存在于字典中,我们将获得与字典中的键名称相关联的值。之后,我们将检查获得的值是否等于给定的值,我们正在检查该值是否存在。
如果两个值都匹配,我们就说输入值对存在于字典中。否则,不会。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
input_value = "Python For Beginners"
print("Input key is:", key)
print("Input value is:", input_value)
try:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary".format(input_value))
else:
print("'{}' is not present in the dictionary".format(input_value))
except KeyError:
print("The key '{}' is not present in the dictionary.".format(key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
Input key is: name
Input value is: Python For Beginners
'Python For Beginners' is present in the dictionary
我们已经得到了上述代码中的关键字'name'。除此之外,我们还有值'Python For Beginners,我们必须检查它是否存在。由于我们只有一个键,在这种情况下,我们刚刚获得了与给定键相关联的值。之后,我们将获得的值与给定的输入值进行比较,以检查输入值是否存在于字典中。
当我们有多个输入键时
现在,我们有多个键,我们需要检查字典中是否存在一个值。这里,我们需要对每个键执行上面讨论的整个操作。
在这种方法中,我们将使用 for 循环遍历作为输入给出的键列表。对于列表中出现的每个键,我们将检索相关联的值,并将其与输入值进行比较。如果两个值都匹配,我们就说输入值存在于字典中。同时,我们将跳出 for 循环。
如果没有一个键有与输入值相等的关联值,我们就说这个值不在字典中。您可以在下面的示例中观察整个过程。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = ["name", 'type']
input_value = "Python For Beginners"
print("Input keys are:", keys)
print("Input value is:", input_value)
valueFound = False
for key in keys:
try:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary".format(input_value))
valueFound = True
break
else:
continue
except KeyError:
print("The key '{}' is not present in the dictionary.".format(key))
if not valueFound:
print("'{}' is not present in the dictionary".format(input_value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
Input keys are: ['name', 'type']
Input value is: Python For Beginners
'Python For Beginners' is present in the dictionary
在使用下标操作符时,如果字典中不存在这个键,程序就会遇到KeyError异常。处理KeyError异常在时间和内存方面代价很高。因此,我们可以通过使用keys()方法或使用 get()方法检查一个键的存在来避免异常。
使用 keys()方法检查字典中是否存在某个值
在字典上调用 keys()方法时,会返回一个包含字典键的dict_keys对象。您可以在下面的结果中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys in the dictionary are:")
print(keys)
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys in the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
当我们只有一个输入键时
为了使用keys()方法检查一个值是否存在于字典中,我们将首先获得字典的键列表。
之后,我们将检查特定键的存在,以确定该键对于现有字典是有效的键。如果输入键出现在键列表中,我们将继续检查字典中是否存在给定值。
对于有效的键,为了检查字典中是否存在该值,我们将获取与字典的键相关联的值。之后,我们将检查获得的值是否等于给定的值,我们正在检查该值是否存在。如果两个值都匹配,我们就说这个值存在于字典中。否则不会。
您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys in the dictionary are:")
print(keys)
key="name"
input_value="Python For Beginners"
if key in keys:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
else:
print("The key '{}' is not present in the dictionary.".format(key))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys in the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
'Python For Beginners' is present in the dictionary.
当我们有多个输入键时
当我们有不止一个键时,我们可以使用 for 循环来遍历键列表。我们将对每个给定的键重复整个过程。如果没有一个键具有与给定值相同的关联值,我们就说该值不在字典中。你可以在下面的例子中观察整个过程。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys in the dictionary are:")
print(keys)
input_keys = ['Aditya',"name", 'type']
input_value = "Python For Beginners"
valueFound = False
for key in input_keys:
if key in keys:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
valueFound = True
break
else:
continue
else:
print("The key '{}' is not present in the dictionary.".format(key))
if not valueFound:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys in the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
The key 'Aditya' is not present in the dictionary.
'Python For Beginners' is present in the dictionary.
使用 get()方法检查字典中是否存在某个值
我们可以使用get()方法来检查字典中是否存在一个值,而不是使用keys() 方法来检查一个键的存在,然后使用下标操作符来获取值。
在字典上调用时,get()方法接受一个键作为输入参数。如果字典中存在该键,它将返回与该键相关联的值,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
print("THe key is '{}'.".format(key))
value = myDict.get(key)
print("THe value is '{}'.".format(value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
THe key is 'name'.
THe value is 'Python For Beginners'.
如果给定的键在字典中不存在,get()方法返回默认值None。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "website"
print("THe key is '{}'.".format(key))
value = myDict.get(key)
print("THe value is '{}'.".format(value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
THe key is 'website'.
THe value is 'None'.
当我们只有一个输入键时
为了使用 get 函数检查字典中是否存在某个值,我们将获取与给定键相关联的值。之后,我们将检查获得的值是否等于给定值。如果是,我们会说该值存在于字典中。否则,不会。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
key = "name"
input_value = "Python For Beginners"
print("The key is '{}'.".format(key))
print("The input value is '{}'.".format(input_value))
value = myDict.get(key)
if value is None:
print("The key '{}' is not present in the dictionary.".format(key))
elif value == input_value:
print("The value '{}' is present in the dictionary.".format(input_value))
else:
print("The value '{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The key is 'name'.
The input value is 'Python For Beginners'.
The value 'Python For Beginners' is present in the dictionary.
当我们有多个输入键时
如果给了我们多个键,我们可以使用 for 循环来遍历键列表。迭代时,我们可以检查每个键的输入值是否存在。如果给定的键都没有与给定值相等的关联值,我们就说该值不在字典中。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = ['Aditya', "name", 'url']
input_value = "Python For Beginners"
print("The input keys are '{}'.".format(keys))
print("The input value is '{}'.".format(input_value))
valueFound=False
for key in keys:
value = myDict.get(key)
if value is None:
print("The key '{}' is not present in the dictionary.".format(key))
elif value == input_value:
print("The value '{}' is present in the dictionary.".format(input_value))
valueFound=True
break
if not valueFound:
print("The value '{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input keys are '['Aditya', 'name', 'url']'.
The input value is 'Python For Beginners'.
The key 'Aditya' is not present in the dictionary.
The value 'Python For Beginners' is present in the dictionary.
到目前为止,我们已经讨论了不同的场景来检查一个值是否存在于一个字典中,当我们被给定一些字典的键时。
现在让我们讨论当没有给定键,而只给定了一个我们必须检查其存在的值时,检查一个值是否存在于字典中的不同方法。
当键不可用时,检查字典中是否存在值
使用 keys()方法检查字典中是否存在某个值
为了使用 keys()方法检查一个值是否存在于字典中,我们将首先通过在字典上执行keys()方法来获得键的列表。
之后,我们将使用下标操作符来获取与键列表中的每个键相关联的字典值。如果任何获得的值等于我们正在检查其存在的值,我们将说该值存在于字典中。否则不会。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
keys = myDict.keys()
isPresent = False
for key in keys:
value = myDict[key]
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
isPresent = True
break
else:
continue
if not isPresent:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
使用 keys()方法检查字典中是否存在多个值
如果我们需要检查字典中是否存在多个值,我们将首先使用如下所示的get()方法和keys()方法获得一个值列表。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys of the dictionary are:")
print(keys)
values = []
for key in keys:
value = myDict.get(key)
values.append(value)
print("The obtained values are '{}'.".format(values))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys of the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
The obtained values are '['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog']'.
这里,我们首先使用keys()方法获得了字典的键。之后,我们创建了一个空列表来存储字典的值。然后,我们使用get()方法获得与字典中每个键相关联的值,并将其存储在列表中。
在获得字典中的值列表后,我们将检查每个输入值是否都在其中。为此,我们可以使用带有成员操作符的 For 循环,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
keys = myDict.keys()
print("The keys of the dictionary are:")
print(keys)
input_values = ["Python For Beginners", "PFB", 'Aditya']
print("The input values are:", input_values)
values = []
for key in keys:
value = myDict.get(key)
values.append(value)
print("The obtained values are '{}'.".format(values))
for value in input_values:
if value in values:
print("The value '{}' is present in the dictionary.".format(value))
else:
print("The value '{}' is not present in the dictionary.".format(value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The keys of the dictionary are:
dict_keys(['name', 'url', 'acronym', 'type'])
The input values are: ['Python For Beginners', 'PFB', 'Aditya']
The obtained values are '['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog']'.
The value 'Python For Beginners' is present in the dictionary.
The value 'PFB' is present in the dictionary.
The value 'Aditya' is not present in the dictionary.
使用 values()方法检查字典中是否存在某个值
在字典上调用values()方法时,它返回包含字典值的dict_values对象的副本。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.values()
print("The values in the dictionary are:")
print(values)
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The values in the dictionary are:
dict_values(['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog'])
为了使用values()方法检查一个值是否存在于字典中,我们将首先通过调用字典上的values()方法获得包含字典值的dict_values对象。
之后,我们将遍历值列表,检查作为用户输入给出的值是否出现在值列表中。如果是,我们会说该值存在于字典中。否则不会。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.values()
print("The values in the dictionary are:")
print(values)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
isPresent = False
for value in values:
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
isPresent = True
break
else:
continue
if not isPresent:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The values in the dictionary are:
dict_values(['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog'])
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
我们可以使用成员操作符“in”来检查给定值是否出现在值列表中,而不是使用 for 循环来遍历值列表。in操作符的语法如下。
element in container_object
in操作符是一个二元操作符,它将一个元素作为第一个操作数,将一个容器对象或迭代器作为第二个操作数。执行后,如果元素存在于容器对象或迭代器中,则返回True。否则,它返回False。
为了检查字典中是否存在给定的值,我们将使用成员操作符检查该值是否存在于由values()方法返回的值列表中,如下例所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.values()
print("The values in the dictionary are:")
print(values)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The values in the dictionary are:
dict_values(['Python For Beginners', 'pythonforbeginners.com', 'PFB', 'python blog'])
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
使用 Values()方法检查字典中是否存在多个值
如果给我们多个值来检查它们的存在,我们将使用一个带有成员操作符的 for 循环和values()方法来检查键的存在。这里,我们将使用 for 循环迭代输入值列表。迭代时,我们将检查当前值是否出现在使用values()方法获得的值列表中。如果是,我们将打印该值存在于字典中。否则不会。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
input_values = ["Python For Beginners", "PFB", 'Aditya']
print("The input values are:", input_values)
values = myDict.values()
for value in input_values:
if value in values:
print("The value '{}' is present in the dictionary.".format(value))
else:
print("The value '{}' is not present in the dictionary.".format(value))
输出:
The dictionary is:
{'name': 'Python For Beginners', 'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog'}
The input values are: ['Python For Beginners', 'PFB', 'Aditya']
The value 'Python For Beginners' is present in the dictionary.
The value 'PFB' is present in the dictionary.
The value 'Aditya' is not present in the dictionary.
使用 viewvalues()方法检查字典中是否存在某个值
如果您使用的是 Python 版,而不是使用 values()方法,那么您可以使用viewvalues() 方法来检查字典中是否存在一个值。
在字典上调用viewvalues()方法时,它返回包含字典中值的新视图的dict_values对象的视图,如下所示。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.viewvalues()
print("The values in the dictionary are:")
print(values)
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The values in the dictionary are:
dict_values(['pythonforbeginners.com', 'PFB', 'python blog', 'Python For Beginners'])
获得dict_values对象后,我们可以检查输入值是否存在于字典中。
为了使用viewvalues()方法检查一个值是否存在于字典中,我们将首先通过调用字典上的viewvalues()方法获得dict_values对象。
之后,我们将遍历dict_values对象,检查作为用户输入给出的值是否出现在值列表中。如果是,我们会说该值存在于字典中。否则不会。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.viewvalues()
print("The values in the dictionary are:")
print(values)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
isPresent = False
for value in values:
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
isPresent = True
break
else:
continue
if not isPresent:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The values in the dictionary are:
dict_values(['pythonforbeginners.com', 'PFB', 'python blog', 'Python For Beginners'])
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
除了使用 for 循环,我们还可以使用如下所示的成员测试来检查输入值在dict_values对象中的存在。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.viewvalues()
print("The values in the dictionary are:")
print(values)
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The values in the dictionary are:
dict_values(['pythonforbeginners.com', 'PFB', 'python blog', 'Python For Beginners'])
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
使用 viewvalues()方法检查字典中是否存在多个值
如果给我们多个值来检查它们的存在,我们将使用一个带有成员操作符的 for 循环和viewvalues()方法来检查键的存在。这里,我们将使用 for 循环迭代输入值列表。迭代时,我们将检查当前值是否出现在使用viewvalues()方法获得的值列表中。如果是,我们将打印该值存在于字典中。否则不会。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.viewvalues()
print("The values in the dictionary are:")
print(values)
input_values = ["Python For Beginners",'PFB','Aditya']
print("The input values are '{}'.".format(input_values))
for input_value in input_values:
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The values in the dictionary are:
dict_values(['pythonforbeginners.com', 'PFB', 'python blog', 'Python For Beginners'])
The input values are '['Python For Beginners', 'PFB', 'Aditya']'.
'Python For Beginners' is present in the dictionary.
'PFB' is present in the dictionary.
'Aditya' is not present in the dictionary.
使用 itervalues()方法检查字典中是否存在某个值
在 python 2 中,我们还可以使用 itervalues()方法来检查一个值是否存在于字典中。
在字典上调用itervalues() 方法时,它返回一个迭代器,我们可以用它迭代字典中的值。
为了使用itervalues()方法检查一个值是否存在于字典中,我们将首先通过在字典上调用 itervalues()方法来获得它返回的迭代器。之后,我们可以使用 for 循环遍历迭代器,并检查输入值是否出现在迭代器中。如果是,我们会说该值存在于字典中。否则不会。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.itervalues()
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
isPresent = False
for value in values:
if value == input_value:
print("'{}' is present in the dictionary.".format(input_value))
isPresent = True
break
else:
continue
if not isPresent:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
除了使用 for 循环,我们还可以使用如下所示的成员测试来检查输入值在dict_values对象中的存在。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.itervalues()
input_value = "Python For Beginners"
print("The input value is '{}'.".format(input_value))
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The input value is 'Python For Beginners'.
'Python For Beginners' is present in the dictionary.
使用 itervalues()方法检查字典中是否存在多个值
如果给我们多个值来检查它们的存在,我们将使用一个带有成员操作符的 for 循环和itervalues() 方法来检查键的存在。
这里,我们将使用 for 循环迭代输入值列表。迭代时,我们将检查当前值是否出现在使用itervalues() 方法获得的值的迭代器中。如果是,我们将打印该值存在于字典中。否则不会。您可以在下面的示例中观察到这一点。
myDict = {"name": "Python For Beginners", "url": "pythonforbeginners.com", "acronym": "PFB", "type": "python blog"}
print("The dictionary is:")
print(myDict)
values = myDict.itervalues()
input_values = ["Python For Beginners",'PFB','Aditya']
print("The input values are '{}'.".format(input_values))
for input_value in input_values:
if input_value in values:
print("'{}' is present in the dictionary.".format(input_value))
else:
print("'{}' is not present in the dictionary.".format(input_value))
输出:
The dictionary is:
{'url': 'pythonforbeginners.com', 'acronym': 'PFB', 'type': 'python blog', 'name': 'Python For Beginners'}
The input values are '['Python For Beginners', 'PFB', 'Aditya']'.
'Python For Beginners' is present in the dictionary.
'PFB' is not present in the dictionary.
'Aditya' is not present in the dictionary.
结论
在本文中,我们讨论了检查字典中是否存在某个值的各种方法。如果您有字典的键,您可以使用使用get()方法的方法来检查一个值是否存在于字典中。如果没有密钥,应该使用 python 3.x 中的values()方法。对于 python 3.x 版,应该使用带有itervalues()方法的方法,因为它是所有方法中最快的。
我希望你喜欢阅读这篇文章。要了解更多关于 python 编程的知识,您可以阅读这篇关于如何在 Python 中删除列表中所有出现的字符的文章。您可能也喜欢这篇关于如何检查 python 字符串是否包含数字的文章。
请继续关注更多内容丰富的文章。
快乐学习!
检查您的外部 IP 地址
原文:https://www.pythonforbeginners.com/code-snippets-source-code/check-your-external-ip-address
概观
这是一个简单的 Python 脚本,用于检查您拥有哪个外部 IP 地址。首先,我们导入 urllib 和 re 模块。
检查您的 IP 地址
我们将用来检查 IP 地址的 URL 是:http://checkip.dyndns.org
import urllib
import re
print "we will try to open this url, in order to get IP Address"
url = "http://checkip.dyndns.org"
print url
request = urllib.urlopen(url).read()
theIP = re.findall(r"d{1,3}.d{1,3}.d{1,3}.d{1,3}", request)
print "your IP Address is: ", theIP
快乐脚本
Python 中的类
原文:https://www.pythonforbeginners.com/basics/classes-in-python
如果你是 python 编程的初学者,你必须了解像整数、浮点数、字符串和复数这样的基本数据类型。此外,您可能已经了解了内置数据结构,如 python 字典、列表、元组和集合。在本文中,我们将学习使用 python 中的类创建复杂的数据类型来存储真实世界对象的信息。
Python 中有哪些类?
正如我们所知,python 是一种面向对象的编程语言,我们可以用 python 创建对象来表示现实世界中的对象。
python 中的对象是标识现实世界对象的属性集合。
例如,如果我们试图用 python 将一个长方体描述为一个对象,我们将指定长方体的长度、宽度和高度的值,并将定义它的属性,如表面积、重量和体积。
为了定义长方体对象的属性,我们使用类。因此,类是 python 中对象的蓝图,类决定了对象的属性和功能。
在我们的长方体例子中,类将是一个构造,它定义了对象的长度、宽度、高度、表面积、重量和体积。定义长方体属性的类将被定义如下。
class Cuboid:
#code for defining constructor
#codes to define methods
如何在 Python 中使用类创建对象?
类只是任何对象的蓝图,它们不能在程序中使用。为了创建由类定义的对象,我们使用类的构造函数来实例化对象。因此,对象也被称为类的实例。
类的构造函数是使用关键字 init()定义的特殊方法。构造函数定义对象的属性,并按如下方式初始化它们。
class Cuboid:
def __init__(self):
self.length=0
self.breadth=0
self.height=0
self.weight=0
我们还可以创建一个构造函数,它将属性值作为输入参数,然后像下面这样初始化它们。
class Cuboid:
def __init__(self, length, breadth, height, weight):
self.length = length
self.breadth = breadth
self.height = height
self.weight = weight
类别属性
对象的属性对于一个类的任何实例都是私有的。与此不同,类属性是类本身的属性,它们由类的每个实例共享。
类属性是在所有方法和构造函数之外的类头下面声明的,如下所示。
class Cuboid:
name = "Cuboid"
def __init__(self, length, breadth, height, weight):
self.length = length
self.breadth = breadth
self.height = height
self.weight = weight
在上面的代码中,我们为长方体类定义了一个类属性“name”。
在类中定义方法
为了定义对象的属性和功能,我们在类中定义方法。方法是在类中定义的函数,用来执行特定的任务并给出一些输出。
例如,从长方体的长度、宽度、高度和重量确定长方体的表面积、体积和密度的方法可以定义如下。
class Cuboid:
name = "Cuboid"
def __init__(self, length, breadth, height, weight):
self.length = length
self.breadth = breadth
self.height = height
self.weight = weight
def volume(self):
x = self.length
y = self.breadth
z = self.height
v = x * y * z
print("The volume is:", v)
def density(self):
x = self.length
y = self.breadth
z = self.height
v = x * y * z
d = self.weight / v
print("Density is:", d)
def surface_area(self):
x = self.length
y = self.breadth
z = self.height
s = 2 * (x * y + y * z + x * z)
print("The surface area is:", s)
定义了一个类的所有属性和方法后,我们可以在 python 程序中使用它来实例化一个对象,并如下使用它们。
class Cuboid:
name = "Cuboid"
def __init__(self, length, breadth, height, weight):
self.length = length
self.breadth = breadth
self.height = height
self.weight = weight
def volume(self):
x = self.length
y = self.breadth
z = self.height
v = x * y * z
print("The volume is:", v)
def density(self):
x = self.length
y = self.breadth
z = self.height
v = x * y * z
d = self.weight / v
print("Density is:", d)
def surface_area(self):
x = self.length
y = self.breadth
z = self.height
s = 2 * (x * y + y * z + x * z)
print("The surface area is:", s)
myCuboid = Cuboid(1, 2, 4,4.5)
myCuboid.density()
myCuboid.surface_area()
myCuboid.volume()
输出:
Density is: 0.5625
The surface area is: 28
The volume is: 8
结论
在本文中,我们研究了 python 中的类的概念。我们还看到了如何使用长方体的例子在类中实现构造函数和方法。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
Python 中的闭包
原文:https://www.pythonforbeginners.com/basics/closures-in-python
你可能听说过 Python 中的 decorators。装饰器是使用闭包实现的。在本文中,我们将研究 python 中的闭包。为了更好地理解闭包,我们将首先研究嵌套函数和自由变量,因为它们是理解 python 中闭包的先决条件。
什么是嵌套函数?
嵌套函数是定义在另一个函数内部的函数。通过作用域规则,嵌套函数可以访问其封闭函数中定义的所有变量。嵌套函数可以使用其封闭函数中的任何非局部变量,但我们不能修改非局部变量,因为默认情况下它处于只读模式。这可以从下面的例子中理解。
def enclosing_function():
myVar = 1117
print("It is enclosing function which encloses a nested function.")
def nested_function(val):
print("I am in nested function and I can access myVar from my enclosing function's scope.")
print("The value of myVar is:", myVar)
temp = myVar + val
print("Value after adding {} to {} is {}.".format(val, myVar, temp))
nested_function(10)
# Execution
enclosing_function()
输出:
It is enclosing function which encloses a nested function.
I am in nested function and I can access myVar from my enclosing function's scope.
The value of myVar is: 1117
Value after adding 10 to 1117 is 1127.
在上面的代码中,我们定义了一个名为 enclosing_function 的封闭函数。在其中,我们定义了一个名为 nested_function 的嵌套函数。在这里,您可以看到我们可以访问在嵌套函数中的封闭函数内声明的变量。
要修改嵌套函数中的非局部变量,可以使用 nonlocal 关键字声明非局部变量。
什么是自由变量?
在程序中,我们只能在声明变量的范围内访问变量。换句话说,如果我们在函数或代码块的范围内声明一个变量,它只能在该范围内被访问。如果我们试图访问范围之外的变量,将会发生 NameError 异常。
在某些情况下,比如嵌套函数,我们可以在定义变量的范围之外访问变量。这种可以在声明范围之外访问的变量称为自由变量。在上面的例子中, myVar 是一个自由变量,因为我们可以在 nested_function 中访问它。
现在我们已经理解了嵌套函数和自由变量的概念,让我们看看 Python 中的闭包是什么。
Python 中的闭包是什么?
闭包是一种我们可以将数据附加到代码上的技术。为了在 Python 中实现闭包,我们使用自由变量和嵌套函数。在封闭函数中定义了嵌套函数后,我们使用 return 语句返回嵌套函数。这里,嵌套函数应该使用自由变量来创建闭包。如果嵌套函数使用自由变量,则嵌套函数称为闭包函数。
闭包函数允许你使用一个变量,即使定义它的作用域已经从内存中移除。通过使用闭包函数,我们可以访问在封闭函数中定义的自由变量,即使封闭函数的作用域已经被破坏。因此,封闭函数中的数据被附加到闭包函数中的代码上。
Python 中闭包存在的条件
对于 Python 中存在的闭包,应该满足某些条件。这些条件如下。
- 在封闭函数中应该定义一个嵌套函数。
- 嵌套函数应该从封闭函数中访问变量。
- 封闭函数应该返回嵌套函数。
Python 中的闭包示例
学习了 Python 中闭包背后的概念之后,让我们看一个例子来更好地理解这个概念。下面是一个 python 程序,用于创建向输入中添加随机数的函数。
import random
def random_addition():
values = [123, 1123, 11123, 111123, 1111123]
def nested_function(val):
x = random.choice(values)
temp = x + val
print("Value after adding {} to {} is {}.".format(val, x, temp))
return nested_function
# Execution
random_function = random_addition()
random_function(10)
random_function(23)
random_function(24)
输出:
Value after adding 10 to 123 is 133.
Value after adding 23 to 1123 is 1146.
Value after adding 24 to 111123 is 111147.
在上面的代码中,我们定义了一个名为 random_addition 的封闭函数。在随机加法中,我们有一个数字列表。在 random_addition 中,我们定义了一个 nested_function ,它接受一个数字作为输入,并从 random_addition 中定义的数字列表中添加一个随机数到输入值中,并打印输出。
如果你仔细观察代码,你会发现函数 random_addition 在程序中只执行了一次,它返回的嵌套函数被赋给了 random_function 变量。一旦随机加法的执行完成,其作用域将从内存中清除。但是,我们可以执行 random_function 任意次,每次我们访问 random_addition 函数中定义的值。即使存储器中不存在 random_addition 的范围,也会发生这种情况。这意味着数据已经附加到代码上,而代码是 Python 中闭包的主要功能。
结论
在本文中,我们讨论了 Python 中的嵌套函数、自由变量和闭包。如果你想避免使用全局变量,闭包是一个很好的工具。闭包也用于在 python 中实现 decorators。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
通过 tespeed 的 speedtest.net 命令行
原文:https://www.pythonforbeginners.com/code-snippets-source-code/command-line-speedtest-net-via-tespeed
概观
在四处寻找命令行工具来检查我的网速时,
我无意中发现了lowendtalk.com上的一个帖子。
这是什么?
这是 speedtest.net 服务器的命令行界面,可以在这里找到:
https://github.com/Janhouse/tespeed
什么是 Speedtest?
Speedtest.net 是一个连接分析网站,用户可以在这里通过分布在世界各地的数百台服务器测试他们的互联网 T2 速度。
在每次测试结束时,用户会看到他们的下载(数据从服务器到他们计算机的速度)和上传(数据从用户计算机发送到服务器的速度)带宽速度。
要求
这个脚本需要 lxml 和 argparse,所以确保首先安装它们。
参见此链接了解操作方法。
在大多数情况下,从终端运行这个命令就足够了: pypm install lxml
脚本是如何工作的?
有关如何使用该程序,请参见 this url
运行脚本
下载需求后,我决定给这个程序一个机会。
将代码从复制并粘贴到这里。
运行脚本
打开你的编辑器,复制并粘贴上面的代码,将文件保存为 speed.py
要执行该程序,请在 shell 中键入 python 和文件名。
$python speed.py
来源
http://www . Jan house . LV/blog/coding/tes speed-terminal-network-speed-test/
https://github.com/Janhouse/tespeed
使用 Python 的 CommandLineFu
原文:https://www.pythonforbeginners.com/code-snippets-source-code/commandlinefu-with-python
概观
练习 Python 编码的最好方法之一是研究一些代码,并亲自尝试。通过做大量的代码练习,您将会对它真正做的事情有更好的理解。
换句话说,边做边学。为了帮助你提高你的 Python 编码技能,我创建了一个程序,它使用了 CommandLineFu.com 的 API
CommandLineFu API
当您想要使用基于 Web 的服务时,常见的第一步是查看它们是否有 API。
幸运的是,Commandlinefu.com提供了一个,可以在这里找到:
“commandlinefu.com 的内容有多种不同的格式,你可以随心所欲。任何包含命令列表的页面(例如按标签、函数或用户列出的列表)都可以以您选择的格式返回,只需简单地更改请求 URL。
他们提供的示例 URL 是:
http://www . command line fu . com/commands/'命令集'/'格式'/
其中:command-set 是指定要返回哪组命令的 URL 组件。
可能的值有:
- 浏览/按投票排序
- 标记的/163/grep
- 匹配/ssh/c3No
格式是下列之一:
- 纯文本
- json
- 简易资讯聚合
我更喜欢使用 json 格式,这也是我在下面的程序中使用的格式。
创建“命令行搜索工具”
我想我们已经有了所有需要的 API 信息,所以让我们开始吧。该计划是有据可查的,应该是直截了当的。
打开一个文本编辑器,复制并粘贴下面的代码。将文件另存为:“commandlinefu.py”并退出编辑器。
#!/usr/bin/env python27
import urllib2
import base64
import json
import os
import sys
import re
os.system("clear")
print "-" * 80
print "Command Line Search Tool"
print "-" * 80
def Banner(text):
print "=" * 70
print text
print "=" * 70
sys.stdout.flush()
def sortByVotes():
Banner('Sort By Votes')
url = "http://www.commandlinefu.com/commands/browse/sort-by-votes/json"
request = urllib2.Request(url)
response = json.load(urllib2.urlopen(request))
#print json.dumps(response,indent=2)
for c in response:
print "-" * 60
print c['command']
def sortByVotesToday():
Banner('Printing All commands the last day (Sort By Votes) ')
url = "http://www.commandlinefu.com/commands/browse/last-day/sort-by-votes/json"
request = urllib2.Request(url)
response = json.load(urllib2.urlopen(request))
for c in response:
print "-" * 60
print c['command']
def sortByVotesWeek():
Banner('Printing All commands the last week (Sort By Votes) ')
url = "http://www.commandlinefu.com/commands/browse/last-week/sort-by-votes/json"
request = urllib2.Request(url)
response = json.load(urllib2.urlopen(request))
for c in response:
print "-" * 60
print c['command']
def sortByVotesMonth():
Banner('Printing: All commands from the last months (Sorted By Votes) ')
url = "http://www.commandlinefu.com/commands/browse/last-month/sort-by-votes/json"
request = urllib2.Request(url)
response = json.load(urllib2.urlopen(request))
for c in response:
print "-" * 60
print c['command']
def sortByMatch():
#import base64
Banner("Sort By Match")
match = raw_input("Please enter a search command: ")
bestmatch = re.compile(r' ')
search = bestmatch.sub('+', match)
b64_encoded = base64.b64encode(search)
url = "http://www.commandlinefu.com/commands/matching/" + search + "/" + b64_encoded + "/json"
request = urllib2.Request(url)
response = json.load(urllib2.urlopen(request))
for c in response:
print "-" * 60
print c['command']
print """
1\. Sort By Votes (All time)
2\. Sort By Votes (Today)
3\. Sort by Votes (Week)
4\. Sort by Votes (Month)
5\. Search for a command
Press enter to quit
"""
while True:
answer = raw_input("What would you like to do? ")
if answer == "":
sys.exit()
elif answer == "1":
sortByVotes()
elif answer == "2":
print sortByVotesToday()
elif answer == "3":
print sortByVotesWeek()
elif answer == "4":
print sortByVotesMonth()
elif answer == "5":
print sortByMatch()
else:
print "Not a valid choice"
当你运行这个程序时,你会看到一个菜单,你可以从中做出选择。
--------------------------------------------------------------------------------
Command Line Search Tool
--------------------------------------------------------------------------------
1\. Sort By Votes (All time)
2\. Sort By Votes (Today)
3\. Sort by Votes (Week)
4\. Sort by Votes (Month)
5\. Search for a command
Press enter to quit
What would you like to do?
...
...
用 Python 注释掉一段代码
原文:https://www.pythonforbeginners.com/code/comment-out-a-block-of-code-in-python
在测试或调试 python 程序时,可能会有很多情况,我们希望代码中的某个语句或代码中的某个语句块不被执行。为此,我们注释掉代码块。在本文中,我们将看到如何使用 python 注释注释掉 python 中的代码块。首先,我们将了解代码块在 python 中的含义,然后我们将了解如何注释掉它们。
什么是代码块?
代码块是任何编程语言中源代码中的一组语句,一旦满足某个条件或调用某个函数,就应该执行这些语句。
在 python 中,通过对语句应用适当的缩进来创建代码块,以创建代码块并将它们与其他代码块分开。
python 中的代码块可以由属于控制语句、函数或类的语句组成。
例如,下面是 if-else 控制语句中的一段代码。
number =int(input())
#This an example of block of code where a block consists of control statement(If else in this case)
if (number%2==0):
print("number is even")
else:
print("number is odd")
函数中的代码块可能如下所示。以下函数将一个数字及其平方作为键值对添加到 python 字典中。
def add_square_to_dict(x,mydict):
#This is an example of block of code where the block consists of an entire function
a=x*x
mydict[str(x)]=a
return mydict
类中的代码块可能如下所示。
class number:
#This is an example of block of code where the block consists of an entire class
def __init__(self,value):
self.value =value
def increment(self):
self.value=self.value+1
通常,一个代码块会扩展到多行。所以要用 python 注释掉一段代码,我们必须使用多行注释。首先我们将看到多行注释的工作,然后我们将尝试注释掉一段代码。
在 python 中处理多行注释
在 python 中,多行注释本质上不是作为一个构造包含在内的。但是单行注释和多行字符串可以用来在 python 中实现多行注释。
我们可以使用单行注释实现多行注释,只要遇到换行符就插入#号。这样,多行注释就被描述为一系列单行注释,如下所示。
def add_square(x,y):
a=x*x
b=y*y
#This is a multi line comment
#implemented using # sign
return a+b
如果我们不把多行字符串赋给任何变量,我们也可以把它们作为多行注释。当字符串没有被赋给任何变量时,它们会被解释器解析和评估,但不会生成字节码,因为没有地址可以赋给字符串。这将影响字符串作为注释的工作。在这个方法中,可以使用三重引号声明多行注释,如下所示。
def add_square(x,y):
a=x*x
b=y*y
"""This is a multiline comment
implemented with the help of
triple quoted strings"""
return a+b
使用# sign 注释掉 python 中的一段代码
我们可以在 python 中注释掉一个代码块,方法是在特定代码块中的每个语句的开头放置一个#符号,如下所示。
number =int(input())
#if (number%2==0):
# print("number is even")
#else:
# print("number is odd")
使用多行字符串注释掉 python 中的代码块
我们可以使用多行字符串方法注释掉一段代码,如下所示。
number =int(input())
"""if (number%2==0):
print("number is even")
else:
print("number is odd")
"""
虽然这种方法可行,但是我们不应该使用多行字符串作为注释来注释掉代码块。原因是多行注释被用作文档字符串来记录源代码。
结论
我们可以使用# symbol 注释掉 python 中的一段代码,但是我们应该避免使用多行字符串来注释掉这段代码。请继续关注更多内容丰富的文章。
如何在 Python 中使用注释
原文:https://www.pythonforbeginners.com/comments/comments-in-python
当使用任何编程语言时,您都需要在代码中包含注释来表示您的工作。这详细说明了代码的某些部分的用途,并让其他开发人员——包括您——知道您编写代码时在做什么。这是一个必要的实践,好的开发者大量使用评论系统。没有它,事情会变得非常混乱,非常快。
如何用 Python 写注释
在 Python 中,有两种方法来注释代码。
第一种是包含注释,详细说明或指出一段代码(或代码片段)的作用。
第二种方法使用多行注释或段落,作为他人阅读您代码的文档。
把第一种想成是对自己的评论,第二种想成是对别人的评论。然而,添加评论的方式没有对错之分。你可以做任何你觉得舒服的事。
单行注释是简单地通过以散列字符(#)开始一行来创建的,它们在行尾自动终止。
例如:
*#This would be a comment in Python*
跨越多行的注释——用于更详细地解释事情——是通过在注释的每一端添加分隔符(" ")来创建的。
*"""
This would be a multiline comment*
*in Python that spans several lines and*
*describes your code, your day, or anything you want it to*
*"""*
请注意:多行注释的推荐方法是每行使用#。(" ")方法实际上不是注释,而是定义了(" ")之间文本的文本常量。它不会显示,但确实存在,可能会导致意外错误。
记得尽可能经常评论。这很重要!
比较 Python 中的两个列表
原文:https://www.pythonforbeginners.com/basics/compare-two-lists-in-python
在 python 中编程时,为了检查不同的条件,必须经常进行比较。对于单个条件检查,我们可能需要比较两个变量或两组变量。在本文中,我们将尝试用不同的方法来比较 python 中的两个列表。在比较时,我们必须检查两个列表是否包含相同的元素,而不考虑元素在列表中出现的顺序。因此,我们必须打印结果。
使用 sort()方法比较两个列表
为了检查两个列表是否包含相同的元素,我们可以首先使用 sort()方法对列表的元素进行排序。然后,我们可以比较两个列表。
为了比较,首先我们将检查列表的长度是否相等。如果长度不相等,列表将被自动视为不同。
如果列表的长度相同,我们将对两个列表进行排序。然后,我们将使用==操作符比较这些列表,以检查这些列表是否相等。如果排序后的列表相等,将确定两个原始列表包含相同的元素。这可以如下实现。
# function to compare lists
def compare(l1, l2):
# here l1 and l2 must be lists
if len(l1) != len(l2):
return False
l1.sort()
l2.sort()
if l1 == l2:
return True
else:
return False
list1 = [1, 2, 3, 4]
list2 = [1, 4, 3, 2]
list3 = [2, 3, 4, 5]
print("list1 is:",list1)
print("list2 is:",list2)
print("list3 is:",list3)
# comparing list1 and list 2
print("list1 and list2 contain same elements:",compare(list1, list2))
#comparing list2 and list3
print("list1 and list3 contain same elements:",compare(list1, list3))
输出:
list1 is: [1, 2, 3, 4]
list2 is: [1, 4, 3, 2]
list3 is: [2, 3, 4, 5]
list1 and list2 contain same elements: True
list1 and list3 contain same elements: False
使用 Python 中的集合进行比较
为了在 python 中比较两个列表,我们可以使用集合。python 中的集合只允许包含唯一值。我们可以利用集合的这个特性来判断两个列表是否有相同的元素。
为了比较,首先我们将检查列表的长度是否相等。如果长度不相等,列表将自动标记为不同。
之后,我们将使用 set()构造函数将列表转换成集合。我们可以使用==运算符来比较这两个集合,以检查这两个集合是否相等。如果两个集合相等,将确定两个列表包含相等的值。下面的例子说明了这个概念。
# function to compare lists
def compare(l1, l2):
# here l1 and l2 must be lists
if len(l1) != len(l2):
return False
set1 = set(l1)
set2 = set(l2)
if set1 == set2:
return True
else:
return False
list1 = [1, 2, 3, 4]
list2 = [1, 4, 3, 2]
list3 = [2, 3, 4, 5]
print("list1 is:", list1)
print("list2 is:", list2)
print("list3 is:", list3)
# comparing list1 and list 2
print("list1 and list2 contain same elements:", compare(list1, list2))
# comparing list2 and list3
print("list1 and list3 contain same elements:", compare(list1, list3))
输出:
list1 is: [1, 2, 3, 4]
list2 is: [1, 4, 3, 2]
list3 is: [2, 3, 4, 5]
list1 and list2 contain same elements: True
list1 and list3 contain same elements: False
使用频率计数器比较两个列表
我们也可以在不比较长度的情况下比较两个列表。为此,首先我们必须为每个列表创建一个 python 字典,它将跟踪列表中元素的频率。在创建了将列表元素存储为键并将它们的频率存储为值的字典之后,我们可以比较两个字典中每个元素的频率。如果每个元素的频率变得相等,将确认两个列表包含相等的元素。
对于这个任务,我们可以使用 counter()方法。当在列表上调用 counter()方法时,它会创建一个 python 字典,并将元素存储为键,将元素的频率存储为值。在调用 counter()方法后,我们可以使用==操作符来比较创建的字典,以检查每个元素的频率是否相等。如果结果为真,则列表包含相等的元素。否则不会。从下面的例子可以看出这一点。
import collections
# function to compare lists
def compare(l1, l2):
# here l1 and l2 must be lists
if len(l1) != len(l2):
return False
counter1 = collections.Counter(l1)
counter2=collections.Counter(l2)
if counter1 == counter2:
return True
else:
return False
list1 = [1, 2, 3, 4]
list2 = [1, 4, 3, 2]
list3 = [2, 3, 4, 5]
print("list1 is:", list1)
print("list2 is:", list2)
print("list3 is:", list3)
# comparing list1 and list 2
print("list1 and list2 contain same elements:", compare(list1, list2))
# comparing list2 and list3
print("list1 and list3 contain same elements:", compare(list1, list3))
输出:
list1 is: [1, 2, 3, 4]
list2 is: [1, 4, 3, 2]
list3 is: [2, 3, 4, 5]
list1 and list2 contain same elements: True
list1 and list3 contain same elements: False
结论
在本文中,我们看到了 python 中比较两个列表的三种不同方法,并检查了它们是否包含相同的元素,而不考虑元素的位置。要阅读更多关于列表的内容,请阅读这篇关于列表理解的文章。
在示例中使用的 compare()函数中,用户可能传递两个其他对象而不是列表。在这种情况下,程序可能会出错。为了避免这种情况,我们可以使用使用 python try except 的异常处理,通过在 try-except 块中使用 type()方法应用类型检查来检查作为参数传递的对象是否是列表,从而避免运行时错误。
Python 中的复数
原文:https://www.pythonforbeginners.com/data-types/complex-numbers-in-python
在进行数据科学、机器学习或科学计算时,我们经常需要对包括复数在内的数字数据类型进行计算。在本文中,我们将学习如何在 python 中定义和使用复数。
什么是复数?
复数是可以写成(a+b j)形式的数,其中 a 和 b 是实数。这里 j 是一个虚数,定义为-1 的平方根。复数成对出现,主要用于计算负数的平方根。
Python 中如何定义复数?
我们可以在 python 中定义复数,只需声明一个变量并指定一个(a+bj)形式的表达式。这里的“a”和“b”应该是一个数字文字,而“j”可以是任何字母字符。我们还可以使用 type()函数检查已定义变量的数据类型,如下所示。
myNum= 3+2j
print("The Number is:")
print(myNum)
print("Data type of Number is:")
print(type(myNum))
输出:
The Number is:
(3+2j)
Data type of Number is:
<class 'complex'>
我们也可以使用 complex()函数定义一个复数。复函数将强制输入作为表示复数的实部的第一参数,将可选输入作为表示复数的虚部的第二参数。我们可以使用 complex()函数定义一个复数,如下所示。
myNum= complex(3,2)
print("The Number is:")
print(myNum)
print("Data type of Number is:")
print(type(myNum))
输出:
The Number is:
(3+2j)
Data type of Number is:
<class 'complex'>
提取复数的实部和虚部
在一个复数(a+b j)中,“a”称为实部,“b”称为虚部。我们可以使用包含值“a”的名为“real”的属性提取复数的实部,并使用包含值“b”的属性“imag”提取虚部,如下所示。
myNum= complex(3,2)
print("The Complex Number is:")
print(myNum)
print("Real part of the complex Number is:")
print(myNum.real)
print("Imaginary part of the complex Number is:")
print(myNum.imag)
输出:
The Complex Number is:
(3+2j)
Real part of the complex Number is:
3.0
Imaginary part of the complex Number is:
2.0
Python 中复数的共轭
对于一个复数(a+ b j),它的共轭定义为复数(a- b j)。我们可以在 python 中使用 conjugate()方法获得任意复数的共轭。在复数上调用 conjugate()方法时,会返回该数字的复共轭。这可以如下进行。
myNum= complex(3,2)
print("The Complex Number is:")
print(myNum)
print("Conjugate of the complex Number is:")
print(myNum.conjugate())
输出:
The Complex Number is:
(3+2j)
Conjugate of the complex Number is:
(3-2j)
复数的大小
复数(a+b j)的大小是(a,b)点到(0,0)的距离。它是代表复数的向量的长度。在 python 中,可以按如下方式计算复数的大小。
import math
def magnitude(num):
x=num.real
y=num.imag
mag=x*x+y*y
return math.sqrt(mag)
myNum= complex(3,2)
print("The Complex Number is:")
print(myNum)
print("Magnitude of the complex Number is:")
print(magnitude(myNum))
输出:
The Complex Number is:
(3+2j)
Magnitude of the complex Number is:
3.605551275463989
结论
在本文中,我们学习了 python 中复数及其属性的基础知识。我们还推导了复数的实部、虚部、共轭和幅度。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
在 Python 中连接数据帧
原文:https://www.pythonforbeginners.com/basics/concatenate-dataframes-in-python
我们使用 python 中的数据帧来处理和分析 python 中的表格数据。在本文中,我们将讨论如何在 python 中连接两个或多个数据帧。
Python 中如何连接数据帧?
要在 python 中连接两个或多个数据帧,我们可以使用 pandas 模块中定义的concat()方法。concat()方法将一列数据帧作为其输入参数,并垂直连接它们。
我们还可以使用concat()方法的 axis 参数水平连接 python 中的数据帧。axis 参数的默认值为 0,表示数据帧将垂直连接。如果要水平连接数据帧,可以将值 1 传递给轴参数。
执行后,concat()方法将返回结果数据帧。
在 python 中垂直连接数据帧
要在 python 中垂直连接两个数据帧,首先需要使用 import 语句导入 pandas 模块。之后,您可以使用concat() 方法连接数据帧,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade2.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2])
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
second dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
Merged dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
如果所有数据帧具有相同的列数,并且列名也相同,则结果数据帧具有与输入数据帧相同的列数。你可以在上面的例子中观察到这一点。
然而,如果一个数据帧的列数少于其他数据帧,则对于从该数据帧获得的行,该列在结果数据帧中的对应值将是 NaN。您可以在下面的示例中观察到这一点。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2])
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 20 72 B
7 24 92 A
second dataframe is:
Roll Name Marks Grade
0 11 Aditya 85 A
1 12 Chris 95 A
2 13 Sam 75 B
3 14 Joel 75 B
4 16 Tom 78 B
5 15 Samantha 55 C
6 20 Tina 72 B
7 24 Amy 92 A
Merged dataframe is:
Roll Marks Grade Name
0 11 85 A NaN
1 12 95 A NaN
2 13 75 B NaN
3 14 75 B NaN
4 16 78 B NaN
5 15 55 C NaN
6 20 72 B NaN
7 24 92 A NaN
0 11 85 A Aditya
1 12 95 A Chris
2 13 75 B Sam
3 14 75 B Joel
4 16 78 B Tom
5 15 55 C Samantha
6 20 72 B Tina
7 24 92 A Amy
如果数据帧具有不同的列名,则在结果数据帧中,每个列名将被分配一个单独的列。此外,对于所获得的数据帧中没有指定列的行,该列的结果数据帧中的相应值将是 NaN。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
在 Python 中水平连接数据帧
为了水平连接数据帧,我们将使用 axis 参数,并在concat() 方法中给出值 1 作为它的输入。执行后,concat()方法将返回水平连接的 dataframe,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2],axis=1)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 20 72 B
7 24 92 A
second dataframe is:
Roll Name Marks Grade
0 11 Aditya 85 A
1 12 Chris 95 A
2 13 Sam 75 B
3 14 Joel 75 B
4 16 Tom 78 B
5 15 Samantha 55 C
6 20 Tina 72 B
7 24 Amy 92 A
Merged dataframe is:
Roll Marks Grade Roll Name Marks Grade
0 11 85 A 11 Aditya 85 A
1 12 95 A 12 Chris 95 A
2 13 75 B 13 Sam 75 B
3 14 75 B 14 Joel 75 B
4 16 78 B 16 Tom 78 B
5 15 55 C 15 Samantha 55 C
6 20 72 B 20 Tina 72 B
7 24 92 A 24 Amy 92 A
如果正在连接的数据帧具有相同数量的记录,则生成的数据帧将不具有任何 NaN 值,如上例所示。但是,如果一个数据帧的行数少于另一个数据帧,则结果数据帧将具有 NaN 值。当连接参数设置为“外部”时,会出现这种情况。
结论
在本文中,我们讨论了如何用 python 连接两个熊猫数据帧。要连接两个以上的数据帧,只需将数据帧添加到数据帧列表中,该列表作为输入提供给concat()方法。
要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于用 python 理解列表的文章。
连接、合并和联接熊猫数据框架
原文:https://www.pythonforbeginners.com/basics/concatenate-merge-and-join-pandas-dataframes
Pandas 数据框架是 python 中分析表格数据的主要工具。在本文中,我们将讨论使用merge() 函数、join()函数和concat()函数连接、合并和联接熊猫数据帧的不同方法。
熊猫 merge()函数
merge()函数用于在 Python 中合并熊猫数据帧。合并的发生方式类似于数据库列中的联接操作。merge()函数的语法如下。
pandas.merge(left_df, right_df, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, suffixes=('_x', '_y'),indicator=False)
这里,
left_df和right_df参数各取一个数据帧作为它们的输入参数。数据帧的位置会影响输出。因此,我们明确地命名了数据帧的位置。“how”参数用于决定将在left_df和right_df上执行的加入操作。它有默认值“inner”,表示将执行内部连接操作。您还可以使用文字“outer”、“left”或“right”分别在数据帧上执行完全外连接、左连接或右连接。on参数用于决定用作连接操作的键的列。这里,提供给 on 参数的列名必须同时出现在left_df和right_df中。如果使用两个数据帧中不同的列名作为连接键,默认情况下 on 参数设置为None。left_on参数用于指定用作来自left_df的连接键的列名。right_on参数用于指定用作来自right_df的连接键的列名。- 如果输入数据帧有任何列作为索引,您可以使用
left_index和right_index参数来使用索引作为连接键。 - 如果您想使用
left_df的索引作为连接键,那么left_index参数被设置为True。它有默认值False。 - 如果您想使用
right_df的索引作为连接键,那么right_index参数被设置为True。它有默认值False。 - 当
left_df和right_df有共同的列名时,使用 suffixes 参数。如果left_df和right_df有共同的列名,_x被添加到left_df中各自的列名,_y被添加到right_df中相同的列名。您也可以使用suffixes参数手动指定后缀。 indicator参数用于指示输入数据帧中是否存在连接键。如果indicator被设置为True,名为“_merge”的附加列被添加到输出数据帧。对于每一行,如果连接键同时出现在left_df和right_df中,则输出为both中的_merge列。如果连接键仅出现在left_df或right_df中,则_merge列中的值将分别为left_only或right_only。
执行后,merge()函数返回输出数据帧。
使用 Merge()函数合并或内部连接数据帧
我们可以使用merge()函数合并两个数据帧。合并功能类似于数据库连接操作。连接数据帧时比较的列被传递给left_on和right_on参数。
在比较左数据帧中的left_on列和右数据帧中的right_on列的值后,将这些行合并以产生输出数据帧。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,left_on="Roll", right_on="Roll")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85 A 1 Aditya
1 12 95 A 1 Chris
2 13 75 B 1 Sam
3 14 75 B 1 Joel
4 16 78 B 1 Samantha
5 15 55 C 1 Tom
6 20 72 B 1 Tina
7 24 92 A 1 Amy
在上面的例子中,我们已经使用"Roll"属性对熊猫数据帧执行了内部连接。从两个数据帧中,"Roll"属性具有相同值的行被合并在一起,以形成输出数据帧的行。
如果输入数据帧有公共列,那么在连接操作之后,后缀_x和_y分别被添加到左和右熊猫数据帧的列名中。您可以在下面的示例中观察到这一点。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_name.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,left_on="Roll", right_on="Roll")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Name Marks Grade
0 11 Aditya 85 A
1 12 Chris 95 A
2 13 Sam 75 B
3 14 Joel 75 B
4 16 Tom 78 B
5 15 Samantha 55 C
6 20 Tina 72 B
7 24 Amy 92 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Name_x Marks Grade Class Name_y
0 11 Aditya 85 A 1 Aditya
1 12 Chris 95 A 1 Chris
2 13 Sam 75 B 1 Sam
3 14 Joel 75 B 1 Joel
4 16 Tom 78 B 1 Samantha
5 15 Samantha 55 C 1 Tom
6 20 Tina 72 B 1 Tina
7 24 Amy 92 A 1 Amy
在这个例子中,两个输入数据帧都有 "Name属性。因此,第一个数据帧的Name列在输出数据帧中得到_x后缀。类似地,第二个数据帧的Name列在输出数据帧中得到后缀_y。
除了默认后缀,我们还可以更改后缀,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_name.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,left_on="Roll", right_on="Roll",suffixes=("_left","_right"))
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Name Marks Grade
0 11 Aditya 85 A
1 12 Chris 95 A
2 13 Sam 75 B
3 14 Joel 75 B
4 16 Tom 78 B
5 15 Samantha 55 C
6 20 Tina 72 B
7 24 Amy 92 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Name_left Marks Grade Class Name_right
0 11 Aditya 85 A 1 Aditya
1 12 Chris 95 A 1 Chris
2 13 Sam 75 B 1 Sam
3 14 Joel 75 B 1 Joel
4 16 Tom 78 B 1 Samantha
5 15 Samantha 55 C 1 Tom
6 20 Tina 72 B 1 Tina
7 24 Amy 92 A 1 Amy
在上面的例子中,我们对第一个数据帧使用了_left后缀,对第二个数据帧使用了_right后缀。您也可以使用"suffixes"参数更改后缀。
使用 merge()函数左连接熊猫数据帧
默认情况下,merge()函数对输入数据帧执行内部连接操作。我们也可以使用左连接操作来合并数据帧。为此,我们可以将文字"left" 传递给how参数。
当我们对 pandas 数据帧执行 left join 操作时,左侧数据帧的所有行都显示在输出数据帧中。对于左侧数据帧中没有右侧数据帧中对应行的行,我们在对应于右侧数据帧的列的行中获得NaN值。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,how="left",left_on="Roll", right_on="Roll",suffixes=("_left","_right"))
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85 A 1.0 Aditya
1 12 95 A 1.0 Chris
2 13 75 B 1.0 Sam
3 14 75 B 1.0 Joel
4 16 78 B 1.0 Samantha
5 15 55 C 1.0 Tom
6 19 75 B NaN NaN
7 20 72 B 1.0 Tina
8 24 92 A 1.0 Amy
9 25 95 A NaN NaN
在上面的例子中,我们在右边的数据帧中没有包含Roll 19和Roll 25的行。但是,它们存在于左边的数据帧中。因此,在左连接操作之后,我们在输出数据帧中得到具有 Roll 19 和 25 的行。然而,右侧数据帧的列在辊 19 和 25 的相应行中具有NaN值。
使用 merge()函数连接熊猫数据帧
类似于左连接操作,我们也可以使用merge()函数对熊猫数据帧执行右连接操作。我们可以通过将文字"right" 传递给"how"参数,使用右连接操作来合并数据帧。
当我们对 pandas 数据帧执行右连接操作时,右数据帧的所有行都显示在输出数据帧中。对于右侧数据帧中在左侧数据帧中没有对应行的行,我们在对应于左侧数据帧的列的行中获得NaN值。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,how="right",left_on="Roll", right_on="Roll",suffixes=("_left","_right"))
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85.0 A 1 Aditya
1 12 95.0 A 1 Chris
2 13 75.0 B 1 Sam
3 14 75.0 B 1 Joel
4 15 55.0 C 1 Tom
5 16 78.0 B 1 Samantha
6 17 NaN NaN 1 Pablo
7 20 72.0 B 1 Tina
8 24 92.0 A 1 Amy
9 30 NaN NaN 1 Justin
10 31 NaN NaN 1 Karl
在本例中,左侧数据帧中没有包含第 17、30 和 31 卷的行。但是,它们存在于正确的数据框架中。因此,在右连接操作之后,我们在输出数据帧中得到具有 Roll 17、30 和 31 的行。然而,左侧数据帧的列在辊 17、30 和 31 的相应行中具有NaN值。
使用 merge()函数完全外部连接 Pandas 数据帧
pandas 数据帧上的内连接、左连接和右连接操作会导致数据丢失。如果希望保留所有输入数据,可以在 pandas 数据帧上执行完全外部连接。为此,您需要将文字"outer"传递给merge()函数中的"how"参数。
在外部连接操作中,左侧数据帧的所有行都显示在输出数据帧中。对于左侧数据帧中没有右侧数据帧中对应行的行,我们在对应于右侧数据帧的列的行中获得NaN值。
类似地,右侧数据帧的所有行都显示在输出数据帧中。对于右侧数据帧中在左侧数据帧中没有对应行的行,我们在对应于左侧数据帧的列的行中获得NaN值。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,how="outer",left_on="Roll", right_on="Roll",suffixes=("_left","_right"))
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85.0 A 1.0 Aditya
1 12 95.0 A 1.0 Chris
2 13 75.0 B 1.0 Sam
3 14 75.0 B 1.0 Joel
4 16 78.0 B 1.0 Samantha
5 15 55.0 C 1.0 Tom
6 19 75.0 B NaN NaN
7 20 72.0 B 1.0 Tina
8 24 92.0 A 1.0 Amy
9 25 95.0 A NaN NaN
10 17 NaN NaN 1.0 Pablo
11 30 NaN NaN 1.0 Justin
12 31 NaN NaN 1.0 Karl
在上面的示例中,我们在右侧数据帧中没有包含第 19 卷和第 25 卷的行。但是,它们存在于左边的数据帧中。因此,在外部连接操作之后,我们在输出数据帧中得到具有 Roll 19 和 25 的行。然而,右侧数据帧的列在辊 19 和 25 的相应行中具有NaN值。
类似地,左侧数据帧中没有包含第 17、30 和 31 卷的行。但是,它们存在于正确的数据框架中。因此,在 n 外部连接操作之后,我们在输出数据帧中得到具有 Roll 17、30 和 31 的行。然而,左侧数据帧的列在辊 17、30 和 31 的相应行中具有NaN值。
使用索引作为连接键合并数据帧
我们也可以使用索引作为连接键来合并数据帧。为此,我们需要根据情况将left_index和right_index参数设置为 True。
例如,我们可以使用左边数据帧的索引作为连接键,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,left_index=True, right_on="Roll")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
19 75 B
20 72 B
24 92 A
25 95 A
second dataframe is:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 1 14 Joel
4 1 15 Tom
5 1 16 Samantha
6 1 17 Pablo
7 1 20 Tina
8 1 24 Amy
9 1 30 Justin
10 1 31 Karl
Merged dataframe is:
Marks Grade Class Roll Name
0 85 A 1 11 Aditya
1 95 A 1 12 Chris
2 75 B 1 13 Sam
3 75 B 1 14 Joel
5 78 B 1 16 Samantha
4 55 C 1 15 Tom
7 72 B 1 20 Tina
8 92 A 1 24 Amy
在本例中,Roll列用作左侧数据帧中的索引。因此,我们不需要将列名传递给left_on参数。背景left_index=True为我们做了工作。
我们也可以使用右边数据帧的索引作为连接键,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,left_on="Roll", right_index=True)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
17 1 Pablo
20 1 Tina
24 1 Amy
30 1 Justin
31 1 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0 11 85 A 1 Aditya
1 12 95 A 1 Chris
2 13 75 B 1 Sam
3 14 75 B 1 Joel
4 16 78 B 1 Samantha
5 15 55 C 1 Tom
7 20 72 B 1 Tina
8 24 92 A 1 Amy
在这个例子中,Roll列被用作右边数据帧中的索引。因此,我们不需要将列名传递给right_on参数。背景right_index=True 为我们做了工作。对于左侧数据帧,我们使用了left_on参数来指定连接键。
要使用两个数据帧的索引,我们可以使用如下所示的left_index和right_index参数。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,left_index=True, right_index=True)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
19 75 B
20 72 B
24 92 A
25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
17 1 Pablo
20 1 Tina
24 1 Amy
30 1 Justin
31 1 Karl
Merged dataframe is:
Marks Grade Class Name
Roll
11 85 A 1 Aditya
12 95 A 1 Chris
13 75 B 1 Sam
14 75 B 1 Joel
16 78 B 1 Samantha
15 55 C 1 Tom
20 72 B 1 Tina
24 92 A 1 Amy
在这个例子中,两个输入数据帧都有Roll列作为它们的索引。因此,我们将left_index和right_index设置为True,以将索引指定为连接键。
用指示器合并熊猫数据帧
在合并数据帧时,我们可以在输出数据帧中添加一些元数据。例如,我们可以指定连接键是否出现在左数据帧、右数据帧或两个输入数据帧中。
为此,我们可以使用指示器参数。当指示器设置为True时,merge()功能会在输出数据帧中添加一个名为_merge的附加列。
对于_merge列中的每一行,如果连接键出现在两个输入数据帧中,则输出值出现在"both"的_merge列中。如果连接键只出现在左侧数据帧中,则_merge列的输出为"left_only"。类似地,如果联接列只出现在右侧数据帧中,则对应行的_merge列中的值将是"right_only"。您可以在下面的示例中观察到这一点。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=pd.merge(df1,df2,how="outer",left_index=True, right_index=True,indicator=True)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
19 75 B
20 72 B
24 92 A
25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
17 1 Pablo
20 1 Tina
24 1 Amy
30 1 Justin
31 1 Karl
Merged dataframe is:
Marks Grade Class Name _merge
Roll
11 85.0 A 1.0 Aditya both
12 95.0 A 1.0 Chris both
13 75.0 B 1.0 Sam both
14 75.0 B 1.0 Joel both
15 55.0 C 1.0 Tom both
16 78.0 B 1.0 Samantha both
17 NaN NaN 1.0 Pablo right_only
19 75.0 B NaN NaN left_only
20 72.0 B 1.0 Tina both
24 92.0 A 1.0 Amy both
25 95.0 A NaN NaN left_only
30 NaN NaN 1.0 Justin right_only
31 NaN NaN 1.0 Karl right_only
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
Pandas concat()函数
我们可以使用 concat()函数水平或垂直连接熊猫数据帧。concat()函数的语法如下。
pandas.concat(objs, axis=0, join='outer', ignore_index=False, keys=None,names=None)
这里,
objs参数是需要连接的数据帧的列表或元组。axis参数用于决定输入数据帧是水平连接还是垂直连接。如果要垂直连接数据帧,轴设置为默认值 0。要水平连接数据帧,轴设置为 1。join参数用于决定如何处理其他索引上的索引。如果我们垂直连接数据帧,join 参数决定输出数据帧中包含哪些列。如果 join 设置为“inner”,则输出数据帧只包含那些出现在所有输入数据帧中的列。如果将 join 设置为默认值“outer”,,则输入数据帧中的所有列都包含在输出数据帧中。如果我们水平连接数据帧,那么连接操作是用输入数据帧的索引来执行的。ignore_index参数用于决定输出数据帧是否存储输入数据帧的索引。默认情况下,它被设置为False,因此输入数据帧的索引被保存在输出数据帧中。当ignore_index设置为True时,输入数据帧的索引被忽略。keys参数用于在输出数据帧中创建额外的索引级别。通常,我们使用该参数来标识输出数据帧中的行或列所属的输入数据帧。这是通过将输入数据帧的名称指定为键来实现的。names参数用于命名使用keys参数创建的索引列。
执行后,concat()函数返回连接的数据帧。
使用 concat()函数垂直连接数据帧
如果我们有两个具有相似数据的数据帧,我们可以使用concat()函数垂直连接它们。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade2.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2])
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
second dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
Merged dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
在上面的示例中,我们在合并所有行后,从输入数据帧创建了输出数据帧。您可以观察到输入数据帧的索引也被连接到输出数据帧中。
要忽略输入数据帧的索引并创建新的索引,可以将concat()函数中的ignore_index参数设置为True,如下例所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade2.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2],ignore_index=True)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
second dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
Merged dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
8 2 27 Harsh 55 C
9 2 23 Clara 78 B
10 3 33 Tina 82 A
11 3 34 Amy 88 A
12 3 15 Prashant 78 B
13 3 27 Aditya 55 C
14 3 23 Radheshyam 78 B
15 3 11 Bobby 50 D
在这里,您可以看到所有的行都被赋予了新的索引。
有时,水平连接的数据帧可能没有相同的列。在这种情况下,输出数据帧中的列是输入数据帧中所有列的并集。例如,考虑下面的例子。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2])
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 20 72 B
7 24 92 A
second dataframe is:
Roll Name Marks Grade
0 11 Aditya 85 A
1 12 Chris 95 A
2 13 Sam 75 B
3 14 Joel 75 B
4 16 Tom 78 B
5 15 Samantha 55 C
6 20 Tina 72 B
7 24 Amy 92 A
Merged dataframe is:
Roll Marks Grade Name
0 11 85 A NaN
1 12 95 A NaN
2 13 75 B NaN
3 14 75 B NaN
4 16 78 B NaN
5 15 55 C NaN
6 20 72 B NaN
7 24 92 A NaN
0 11 85 A Aditya
1 12 95 A Chris
2 13 75 B Sam
3 14 75 B Joel
4 16 78 B Tom
5 15 55 C Samantha
6 20 72 B Tina
7 24 92 A Amy
在上面的例子中,第一个数据帧包含列"Roll", "Marks", 和 "Grade"。第二个数据帧包含列"Roll", "Name", "Marks", 和 "Grade"。因此,输出数据帧包含列"Roll", "Name", "Marks", 和 "Grade"。
对应于第一个数据帧的行中的“Name”列中的值将包含NaN值,因为第一个数据帧不包含"Name"列。类似地,如果第二个数据帧具有额外的列,则对应于第一个数据帧的行将包含相应列的NaN值。
使用 Concat()函数水平连接数据帧
我们也可以使用concat()函数水平连接数据帧。为此,我们需要使用concat()函数中的参数axis=1 。
当使用concat()功能水平连接两个数据帧时,使用数据帧的索引值合并输入数据帧的行。在执行了concat()函数之后,我们得到了如下所示的输出数据帧。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2],axis=1)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 20 72 B
7 24 92 A
second dataframe is:
Roll Name Marks Grade
0 11 Aditya 85 A
1 12 Chris 95 A
2 13 Sam 75 B
3 14 Joel 75 B
4 16 Tom 78 B
5 15 Samantha 55 C
6 20 Tina 72 B
7 24 Amy 92 A
Merged dataframe is:
Roll Marks Grade Roll Name Marks Grade
0 11 85 A 11 Aditya 85 A
1 12 95 A 12 Chris 95 A
2 13 75 B 13 Sam 75 B
3 14 75 B 14 Joel 75 B
4 16 78 B 16 Tom 78 B
5 15 55 C 15 Samantha 55 C
6 20 72 B 20 Tina 72 B
7 24 92 A 24 Amy 92 A
如果任何输入数据帧包含其它数据帧中不存在的额外的行或索引,则输出数据帧在对应于相应行中的其它数据帧的列中包含NaN值。您可以在下面的示例中观察到这一点。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2],axis=1)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 20 72 B
7 24 92 A
second dataframe is:
Roll Name Marks Grade
0 11 Aditya 85 A
1 12 Chris 95 A
2 13 Sam 75 B
3 14 Joel 75 B
4 16 Tom 78 B
5 15 Samantha 55 C
6 20 Tina 72 B
7 24 Amy 92 A
8 25 Sinu 95 A
Merged dataframe is:
Roll Marks Grade Roll Name Marks Grade
0 11.0 85.0 A 11 Aditya 85 A
1 12.0 95.0 A 12 Chris 95 A
2 13.0 75.0 B 13 Sam 75 B
3 14.0 75.0 B 14 Joel 75 B
4 16.0 78.0 B 16 Tom 78 B
5 15.0 55.0 C 15 Samantha 55 C
6 20.0 72.0 B 20 Tina 72 B
7 24.0 92.0 A 24 Amy 92 A
8 NaN NaN NaN 25 Sinu 95 A
在本例中,您可以看到最后一行包含与第一个数据帧对应的列的NaN值。这是因为第一个数据帧比第二个数据帧少包含一行。
仅用公共行索引水平连接数据帧
如果不希望NaN值出现在输出数据帧中,可以使用如下所示的join="inner" 参数。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2],join="inner",axis=1)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 20 72 B
7 24 92 A
second dataframe is:
Roll Name Marks Grade
0 11 Aditya 85 A
1 12 Chris 95 A
2 13 Sam 75 B
3 14 Joel 75 B
4 16 Tom 78 B
5 15 Samantha 55 C
6 20 Tina 72 B
7 24 Amy 92 A
8 25 Sinu 95 A
Merged dataframe is:
Roll Marks Grade Roll Name Marks Grade
0 11 85 A 11 Aditya 85 A
1 12 95 A 12 Chris 95 A
2 13 75 B 13 Sam 75 B
3 14 75 B 14 Joel 75 B
4 16 78 B 16 Tom 78 B
5 15 55 C 15 Samantha 55 C
6 20 72 B 20 Tina 72 B
7 24 92 A 24 Amy 92 A
用自定义索引水平连接数据帧
当我们水平连接数据帧时,使用默认索引来匹配行。如果我们指定输入数据帧的索引,则使用索引值作为关键字来匹配数据帧的行。您可以在下面的示例中观察到这一点。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2],join="inner",axis=1)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
20 72 B
24 92 A
second dataframe is:
Name Marks Grade
Roll
11 Aditya 85 A
12 Chris 95 A
13 Sam 75 B
14 Joel 75 B
16 Tom 78 B
15 Samantha 55 C
20 Tina 72 B
24 Amy 92 A
25 Sinu 95 A
Merged dataframe is:
Marks Grade Name Marks Grade
Roll
11 85 A Aditya 85 A
12 95 A Chris 95 A
13 75 B Sam 75 B
14 75 B Joel 75 B
16 78 B Tom 78 B
15 55 C Samantha 55 C
20 72 B Tina 72 B
24 92 A Amy 92 A
在连接数据帧后向行添加标识符
当我们连接两个数据帧时,输出数据帧并不指定特定行属于哪个输入数据帧。要指定这一点,我们可以使用"keys"参数。"keys"参数接受一个字符串列表作为它的输入。执行后,它将关键字作为额外级别的索引添加到输出数据帧中。在"keys"参数中指定的每个键对应一个特定的数据帧。您可以在下面的示例中观察到这一点。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade2.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2],keys=["Dataframe1","dataframe2"])
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
second dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
Merged dataframe is:
Class Roll Name Marks Grade
Dataframe1 0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
dataframe2 0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
在上面的示例中,您可以看到我们在输出数据帧中添加了“dataframe1”和“dataframe2”作为额外的索引级别。您还可以使用如下所示的“names”参数为索引列命名。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade2.csv")
print("second dataframe is:")
print(df2)
df3=pd.concat([df1,df2],keys=["Dataframe1","dataframe2"],names=["Dataframe","index"])
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Class Roll Name Marks Grade
0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
second dataframe is:
Class Roll Name Marks Grade
0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
Merged dataframe is:
Class Roll Name Marks Grade
Dataframe index
Dataframe1 0 1 11 Aditya 85 A
1 1 12 Chris 95 A
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
4 1 15 Harry 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
7 2 15 Golu 79 B
dataframe2 0 2 27 Harsh 55 C
1 2 23 Clara 78 B
2 3 33 Tina 82 A
3 3 34 Amy 88 A
4 3 15 Prashant 78 B
5 3 27 Aditya 55 C
6 3 23 Radheshyam 78 B
7 3 11 Bobby 50 D
熊猫加入()方法
代替merge()函数,我们也可以使用join()方法在两个数据帧上执行连接。
join()方法的语法如下。
df.join(other, on=None, how='left', lsuffix='', rsuffix='’)
这里,
- 是我们左边的数据帧。
- 如果我们想要连接多个数据帧,参数
“other”表示要连接的正确数据帧或数据帧列表。 on参数用于指定用作连接键的列。- “
how”参数用于指定是执行左连接、右连接、内连接还是全外连接。默认情况下,它的值为“left”。 - 当左右数据帧具有共同的列名时,
lsuffix和rsuffix参数用于指定输出数据帧中来自输入数据帧的列的后缀。
当使用数据帧的索引作为连接键执行连接时,join() 方法工作得最好。
使用 Join()方法左连接熊猫数据帧
默认情况下, join()方法执行左连接操作。当在一个数据帧上调用时,它将另一个数据帧作为其输入参数。执行后,它返回连接的数据帧。使用索引列作为连接键来连接输入数据帧。
在这里,我想强调的是,join()方法最适合具有定制索引列的数据帧。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=df1.join(df2)
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
19 75 B
20 72 B
24 92 A
25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
17 1 Pablo
20 1 Tina
24 1 Amy
30 1 Justin
31 1 Karl
Merged dataframe is:
Marks Grade Class Name
Roll
11 85 A 1.0 Aditya
12 95 A 1.0 Chris
13 75 B 1.0 Sam
14 75 B 1.0 Joel
16 78 B 1.0 Samantha
15 55 C 1.0 Tom
19 75 B NaN NaN
20 72 B 1.0 Tina
24 92 A 1.0 Amy
25 95 A NaN NaN
使用 Join()方法右连接熊猫数据帧
我们可以使用如下所示的join()方法对 pandas 数据帧执行右连接操作。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=df1.join(df2,how="right")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
19 75 B
20 72 B
24 92 A
25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
17 1 Pablo
20 1 Tina
24 1 Amy
30 1 Justin
31 1 Karl
Merged dataframe is:
Marks Grade Class Name
Roll
11 85.0 A 1 Aditya
12 95.0 A 1 Chris
13 75.0 B 1 Sam
14 75.0 B 1 Joel
15 55.0 C 1 Tom
16 78.0 B 1 Samantha
17 NaN NaN 1 Pablo
20 72.0 B 1 Tina
24 92.0 A 1 Amy
30 NaN NaN 1 Justin
31 NaN NaN 1 Karl
使用 Join()方法内部连接数据帧
我们可以通过将参数how="inner"传递给 join() 方法来对 pandas 数据帧执行内部连接操作,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=df1.join(df2,how="inner")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
19 75 B
20 72 B
24 92 A
25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
17 1 Pablo
20 1 Tina
24 1 Amy
30 1 Justin
31 1 Karl
Merged dataframe is:
Marks Grade Class Name
Roll
11 85 A 1 Aditya
12 95 A 1 Chris
13 75 B 1 Sam
14 75 B 1 Joel
16 78 B 1 Samantha
15 55 C 1 Tom
20 72 B 1 Tina
24 92 A 1 Amy
使用 Join()方法的外部连接数据帧
我们可以使用如下例所示的join()方法在 pandas 数据帧上执行外部连接。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=df1.join(df2,how="outer")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
19 75 B
20 72 B
24 92 A
25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
17 1 Pablo
20 1 Tina
24 1 Amy
30 1 Justin
31 1 Karl
Merged dataframe is:
Marks Grade Class Name
Roll
11 85.0 A 1.0 Aditya
12 95.0 A 1.0 Chris
13 75.0 B 1.0 Sam
14 75.0 B 1.0 Joel
15 55.0 C 1.0 Tom
16 78.0 B 1.0 Samantha
17 NaN NaN 1.0 Pablo
19 75.0 B NaN NaN
20 72.0 B 1.0 Tina
24 92.0 A 1.0 Amy
25 95.0 A NaN NaN
30 NaN NaN 1.0 Justin
31 NaN NaN 1.0 Karl
用公共列名连接数据框架
如果输入数据帧有共同的列名,我们需要使用参数rsuffix和lsuffix为数据帧的列指定后缀,如下所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=df1.join(df2,on="Roll",how="outer",lsuffix="_left", rsuffix="_right")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Name Marks Grade
Roll
11 Aditya 85 A
12 Chris 95 A
13 Sam 75 B
14 Joel 75 B
16 Tom 78 B
15 Samantha 55 C
20 Tina 72 B
24 Amy 92 A
25 Sinu 95 A
Merged dataframe is:
Roll Marks_left Grade_left Name Marks_right Grade_right
0 11 85 A Aditya 85.0 A
1 12 95 A Chris 95.0 A
2 13 75 B Sam 75.0 B
3 14 75 B Joel 75.0 B
4 16 78 B Tom 78.0 B
5 15 55 C Samantha 55.0 C
6 19 75 B NaN NaN NaN
7 20 72 B Tina 72.0 B
8 24 92 A Amy 92.0 A
9 25 95 A Sinu 95.0 A
在这个例子中,Marks和Grade列出现在两个输入数据帧中。因此,我们需要为列名指定后缀。
如果不指定后缀,并且输入数据帧有公共的列名,程序就会出错。
使用列名作为连接键连接数据帧
如果调用了join()方法的 dataframe 没有连接键作为索引列,您可以使用"on"参数指定列名。但是,作为输入参数传递的 dataframe 需要将用作连接键的列作为其索引。您可以在下面的示例中观察到这一点。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data1.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=df1.join(df2,on="Roll",how="outer")
print("Merged dataframe is:")
print(df3)
输出:
First dataframe is:
Roll Marks Grade
0 11 85 A
1 12 95 A
2 13 75 B
3 14 75 B
4 16 78 B
5 15 55 C
6 19 75 B
7 20 72 B
8 24 92 A
9 25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
17 1 Pablo
20 1 Tina
24 1 Amy
30 1 Justin
31 1 Karl
Merged dataframe is:
Roll Marks Grade Class Name
0.0 11 85.0 A 1.0 Aditya
1.0 12 95.0 A 1.0 Chris
2.0 13 75.0 B 1.0 Sam
3.0 14 75.0 B 1.0 Joel
4.0 16 78.0 B 1.0 Samantha
5.0 15 55.0 C 1.0 Tom
6.0 19 75.0 B NaN NaN
7.0 20 72.0 B 1.0 Tina
8.0 24 92.0 A 1.0 Amy
9.0 25 95.0 A NaN NaN
NaN 17 NaN NaN 1.0 Pablo
NaN 30 NaN NaN 1.0 Justin
NaN 31 NaN NaN 1.0 Karl
使用 Join()方法连接多个数据帧
我们也可以使用join() 方法连接多个数据帧。为此,我们需要在一个数据帧上调用join()方法,并将列表中的其他数据帧作为输入传递给join()方法。
这里,我们需要确保所有的数据帧都应该将连接键作为它们的索引列。此外,除了索引列之外,任何两个数据帧之间都不应该有一个公共列。遵循这两个条件,我们可以使用如下所示的join() 方法连接多个 pandas 数据帧。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("name_data.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=pd.read_csv("height_with_roll.csv",index_col="Roll")
print("Third dataframe is:")
print(df3)
df4=df1.join([df2,df3])
print("Merged dataframe is:")
print(df4)
输出:
First dataframe is:
Marks Grade
Roll
11 85 A
12 95 A
13 75 B
14 75 B
16 78 B
15 55 C
19 75 B
20 72 B
24 92 A
25 95 A
second dataframe is:
Class Name
Roll
11 1 Aditya
12 1 Chris
13 1 Sam
14 1 Joel
15 1 Tom
16 1 Samantha
20 1 Tina
24 1 Amy
Third dataframe is:
Height
Roll
11 170
12 165
13 155
14 180
16 140
15 162
19 175
20 163
24 154
25 161
Merged dataframe is:
Marks Grade Class Name Height
Roll
11 85 A 1.0 Aditya 170
12 95 A 1.0 Chris 165
13 75 B 1.0 Sam 155
14 75 B 1.0 Joel 180
16 78 B 1.0 Samantha 140
15 55 C 1.0 Tom 162
19 75 B NaN NaN 175
20 72 B 1.0 Tina 163
24 92 A 1.0 Amy 154
25 95 A NaN NaN 161
如果输入数据帧有共同的列名,程序将运行到ValueError异常,如下例所示。
import numpy as np
import pandas as pd
df1=pd.read_csv("grade_with_roll1.csv",index_col="Roll")
print("First dataframe is:")
print(df1)
df2=pd.read_csv("grade_with_name.csv",index_col="Roll")
print("second dataframe is:")
print(df2)
df3=pd.read_csv("height_with_roll.csv",index_col="Roll")
print("Third dataframe is:")
print(df3)
df4=df1.join([df2,df3])
print("Merged dataframe is:")
print(df4)
输出:
ValueError: Indexes have overlapping values: Index(['Marks', 'Grade'], dtype='object')
结论
在本文中,我们讨论了如何在 python 中合并、连接和联接 pandas 数据帧。。要了解更多关于 python 编程的知识,你可以阅读这篇关于如何创建熊猫数据框架的文章。您可能也会喜欢这篇关于 Python 中的字符串操作的文章。
用 Python 将字典转换成元组列表
原文:https://www.pythonforbeginners.com/dictionary/convert-a-dictionary-to-list-of-tuples-in-python
我们知道 python 中的字典包含键值对。在本文中,我们将把一个 python 字典转换成一个元组列表,其中每个元组包含一个键值对。
使用 for 循环将字典转换为元组列表
我们可以使用 for 循环,通过逐个访问字典的键和值,将一个 python 字典转换为元组列表。首先,我们将使用键和值创建元组,然后我们将把它们附加到一个列表中,如下所示。
myDict = {1: 2, 3: 4, 5: 6, 7: 8}
print("The Dictionary is:",myDict)
myList = []
for key in myDict:
value = myDict[key]
myTuple = (key, value)
myList.append(myTuple)
print("The list of tuples is:",myList)
输出:
The Dictionary is: {1: 2, 3: 4, 5: 6, 7: 8}
The list of tuples is: [(1, 2), (3, 4), (5, 6), (7, 8)]
使用 items()方法将字典转换为元组列表
当在字典上调用 items()方法时,它返回一个 dict_items 对象。dict_items 对象包含字典的键值对。我们可以使用 list()方法将 dict_items 转换为列表,如下所示。
myDict = {1: 2, 3: 4, 5: 6, 7: 8}
print("The Dictionary is:", myDict)
items = myDict.items()
myList = list(items)
print("The list of tuples is:", myList)
输出:
The Dictionary is: {1: 2, 3: 4, 5: 6, 7: 8}
The list of tuples is: [(1, 2), (3, 4), (5, 6), (7, 8)]
不使用 list()函数,我们可以使用 list comprehension 将 dict_items 转换为一个列表,如下所示。
myDict = {1: 2, 3: 4, 5: 6, 7: 8}
print("The Dictionary is:", myDict)
items = myDict.items()
myList = [item for item in items]
print("The list of tuples is:", myList)
输出:
The Dictionary is: {1: 2, 3: 4, 5: 6, 7: 8}
The list of tuples is: [(1, 2), (3, 4), (5, 6), (7, 8)]
使用 zip()函数将字典转换为元组列表
我们可以使用 zip()函数创建一个包含键值对的元组列表。zip()函数将列表等可迭代对象作为输入,并将它们合并成一个可迭代对象。合并时,zip()函数在每个 iterable 的相同索引处创建元素元组。
例如,如果我们将两个列表[1,2,3]和[4,5,6]传递给 zip()函数,它会将这两个列表合并成[(1,4),(2,5),(3,6)]。即来自每个 iterable 的相同索引处的元素被压缩在一起。
为了使用 zip()函数将字典转换成元组列表,我们将把键列表和值列表作为输入传递给 zip()函数。
我们可以使用 keys()方法获得密钥列表。当在字典上调用 keys()方法时,它返回一个包含字典键的 dict_keys 对象。我们可以使用 list()函数将 dict_keys 对象转换成一个列表。
类似地,我们可以使用 values()方法获得值列表。在字典上调用 values()方法时,会返回一个包含字典值的 dict_values 对象。我们可以使用 list()函数将 dict_values 对象转换成一个列表。
我们可以使用 keys()和 values()方法以及 zip()函数将字典转换为元组列表,如下所示。
myDict = {1: 2, 3: 4, 5: 6, 7: 8}
print("The Dictionary is:", myDict)
keys = list(myDict.keys())
values = list(myDict.values())
myList = list(zip(keys, values))
print("The list of tuples is:", myList)
输出:
The Dictionary is: {1: 2, 3: 4, 5: 6, 7: 8}
The list of tuples is: [(1, 2), (3, 4), (5, 6), (7, 8)]
结论
在本文中,我们讨论了用 Python 将字典转换成元组列表的不同方法。我们使用 for 循环、list comprehension 和 zip()函数以及 items()、key()和 values()等字典方法将字典转换为元组列表。
在 Python 中将包含浮点数的列表转换为字符串
原文:https://www.pythonforbeginners.com/lists/convert-a-list-containing-float-numbers-to-string-in-python
在 python 中工作时,我们可能需要将包含浮点数的列表转换为字符串。在本文中,我们将研究不同的方法来将包含浮点数的列表转换为包含列表元素的字符串,以空格分隔子字符串的形式。
将包含浮点数的列表转换为字符串的任务的重要函数
要将浮点数列表转换为字符串,我们需要几个字符串方法,我们将首先讨论这些方法,然后执行操作。
str()函数
str()函数将整数文字、浮点文字或任何其他给定的输入转换为字符串文字,并在转换后返回输入的字符串文字。这可以如下进行。
float_num=10.0
str_num=str(float_num)
join()方法
在分隔符上调用方法,字符串的可迭代对象作为输入传递给方法。它用分隔符连接 iterable 对象中的每个字符串,并返回一个新字符串。
join()方法的语法与separator.join(iterable)相同,其中分隔符可以是任何字符,iterable 可以是列表或元组等。这可以这样理解。
str_list=["I","am","Python","String"]
print("List of strings is:")
print(str_list)
separator=" "
str_output=separator.join(str_list)
print("String output is:")
print(str_output)
输出:
List of strings is:
['I', 'am', 'Python', 'String']
String output is:
I am Python String
map()函数
map()函数将一个函数(函数是第一类对象,在 python 中可以作为参数传递)和一个 iterable 作为参数,对 iterable 对象的每个元素执行函数,并返回可以转换为任何 iterable 的输出 map 对象。
map()函数的语法是map(function,iterable)。这可以这样理解。
float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
str_list=list(map(str,float_list))
print("List of String numbers is:")
print(str_list)
输出:
List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
List of String numbers is:
['10.0', '11.2', '11.7', '12.1']
现在我们将看到如何使用上述函数将包含浮点数的列表转换为字符串。
使用 for 循环将包含浮点数的列表转换为字符串
我们可以将浮点数列表转换为字符串,方法是声明一个空字符串,然后执行字符串连接将列表元素添加到字符串中,如下所示。
float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
float_string=""
for num in float_list:
float_string=float_string+str(num)+" "
print("Output String is:")
print(float_string.rstrip())
输出:
List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
Output String is:
10.0 11.2 11.7 12.1
在上面的程序中,输出字符串在末尾包含一个额外的空格,必须使用rstrip()方法将其删除。为了避免这个额外的操作,我们可以使用 join()方法,而不是通过添加字符串来创建输出字符串来执行连接操作,如下所示。
float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
float_string=""
for num in float_list:
float_string=" ".join([float_string,str(num)])
print("Output String is:")
print(float_string.lstrip())
输出
List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
Output String is:
10.0 11.2 11.7 12.1
在上面的方法中,在输出字符串的左侧添加了一个额外的空格,必须使用lstrip()方法将其删除。为了避免这种情况,我们可以使用 map()函数将浮点数列表转换为字符串列表,然后使用join()方法执行字符串连接,得到如下输出字符串,而不是对列表的每个元素应用str()函数。
float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
str_list=list(map(str,float_list))
print("List of String numbers is:")
print(str_list)
float_string=""
for num in float_list:
float_string=" ".join(str_list)
print("Output String is:")
print(float_string)
输出:
List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
List of String numbers is:
['10.0', '11.2', '11.7', '12.1']
Output String is:
10.0 11.2 11.7 12.1
使用列表理解将包含浮点数的列表转换为字符串
代替 for 循环,我们可以使用 list comprehension 来执行浮点数列表到字符串的转换,如下所示。我们可以使用 join()方法来理解列表,如下所示。
float_list=[10.0,11.2,11.7,12.1]
print("List of floating point numbers is:")
print(float_list)
str_list=[str(i) for i in float_list]
print("List of floating string numbers is:")
print(str_list)
float_string=" ".join(str_list)
print("Output String is:")
print(float_string)
输出:
List of floating point numbers is:
[10.0, 11.2, 11.7, 12.1]
List of floating string numbers is:
['10.0', '11.2', '11.7', '12.1']
Output String is:
10.0 11.2 11.7 12.1
结论
在本文中,我们看到了如何使用不同的字符串方法(如str()、join())将包含浮点数的列表转换为字符串,以及 python 中的循环或列表理解。请继续关注更多内容丰富的文章。
在 Python 中将字符串列表转换为整型
原文:https://www.pythonforbeginners.com/basics/convert-a-list-of-strings-to-ints-in-python
在 python 中,我们使用列表来存储不同的元素。在本文中,我们将讨论将字符串列表转换为整型的不同方法。我们还将讨论如何在 python 中将字符串列表转换成整型。
int()函数
int() 函数将一个字符串或浮点文字作为其输入参数,并返回一个整数,如下所示。
myStr = "11"
print("data type of {} is {}".format(myStr, type(myStr)))
myInt = int(myStr)
print("data type of {} is {}".format(myInt, type(myInt)))
输出:
data type of 11 is <class 'str'>
data type of 11 is <class 'int'>
如果int()函数的输入不能转换成整数,程序运行到ValueError异常,并以消息“[ValueError: invalid literal for int() with base 10](ValueError: invalid literal for int() with base 10)终止。您可以在下面的示例中观察到这一点。
myStr = "Aditya"
print("data type of {} is {}".format(myStr, type(myStr)))
myInt = int(myStr)
print("data type of {} is {}".format(myInt, type(myInt)))
输出:
data type of Aditya is <class 'str'>
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myInt = int(myStr)
ValueError: invalid literal for int() with base 10: 'Aditya'
为了避免异常,我们可以首先检查输入是否可以转换为整数。浮点数将总是被转换成整数。然而,当int()函数的输入是一个字符串并且由字符而不是数字组成时,就会发生ValueError异常。因此,要将字符串转换为整数,我们首先要检查它是否只由数字组成。为此,我们将使用isdigit()方法。
isdigit()方法
在字符串上调用isdigit()方法时,如果字符串仅由十进制数字组成,则返回 true,如下所示。
myStr = "11"
is_digit = myStr.isdigit()
print("{} consists of only digits:{}".format(myStr, is_digit))
输出:
11 consists of only digits:True
如果字符串包含除十进制数字之外的任何其他字符,isdigit()方法将返回False。您可以在下面的示例中观察到这一点。
myStr = "Aditya"
is_digit = myStr.isdigit()
print("{} consists of only digits:{}".format(myStr, is_digit))
输出:
Aditya consists of only digits:False
在将字符串转换为整数时,我们可以使用isdigit()方法来避免 ValueError 异常。为此,我们将首先调用字符串上的isdigit()方法。如果它返回True,我们将使用int()函数将字符串转换为整数。否则,我们会说字符串不能转换成整数。您可以在下面的示例中观察到这一点。
myStr = "Aditya"
is_digit = myStr.isdigit()
if is_digit:
myInt=int(myStr)
print("The integer is:",myInt)
else:
print("'{}' cannot be converted into integer.".format(myStr))
输出:
'Aditya' cannot be converted into integer.
既然我们已经讨论了int()函数和isdigit() method, let's函数的工作原理,现在我们来讨论在 python 中将字符串列表转换成整型的不同方法。
使用 Python 中的 for 循环将字符串列表转换为整数
要在 python 中将字符串列表转换为整型,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储整数。 - 之后,我们将使用 for 循环遍历字符串列表。
- 在迭代时,我们将首先检查当前字符串是否可以使用
isdigit()方法转换为 int。 - 如果字符串可以转换成 int,我们就用
int()函数把字符串转换成 int。否则,我们会说当前字符串不能转换成整数。 - 在将字符串转换成 int 之后,我们将使用
append()方法将它附加到new_list中。在new_list上调用append()方法时,该方法将新创建的整数作为其输入参数,并将其添加到new_list。 - 最后,我们将移动到输入列表中的下一个字符串。
在执行 for 循环后,我们将在new_list中获得 int 的列表。您可以在下面的示例中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = []
for string in myList:
is_digit = string.isdigit()
if is_digit:
myInt = int(string)
new_list.append(myInt)
else:
print("'{}' cannot be converted into an integer.".format(string))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出:
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
使用 Python 中的 for 循环将字符串列表转换为整型
要使用 for 循环、int()函数和isdigit()函数将字符串列表的列表转换为整型,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储列表的输出列表。 - 之后,我们将使用 for 循环遍历输入列表的内部列表。
- 在 for 循环中,我们将创建一个名为
temp_list的空列表来存储从内部列表中获得的 int 列表。 - 然后,我们将使用另一个 for 循环迭代每个内部列表的元素。
- 在迭代内部列表的元素时,我们将首先检查当前字符串是否可以使用
isdigit()方法转换为 int。 - 如果字符串可以转换成 int,我们就用
int()函数把字符串转换成 int。否则,我们会说当前字符串不能转换成整数。然后,我们将移动到当前内部列表中的下一个字符串。 - 在将当前内部列表的所有字符串转换成整数后,我们还将使用
append()方法将它们附加到temp_list中。 - 迭代完每个内部循环后,我们将使用
append()方法将temp_list添加到new_list中。然后,我们将移动到列表列表中的下一个内部列表。
执行 for 循环后,我们将获得包含整数元素而不是字符串的列表,如下例所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
temp_list = []
for element in inner_list:
is_digit = element.isdigit()
if is_digit:
myInt = int(element)
temp_list.append(myInt)
else:
print("'{}' cannot be converted into an integer.".format(element))
new_list.append(temp_list)
print("The list of lists of ints is:")
print(new_list)
输出:
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into an integer.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
在上面的示例中,字符串“Aditya”不能转换为 int。因此,它已从输出中省略。
使用列表理解将字符串列表转换为整数
python 中的 List comprehension 用于从现有的容器对象创建新的列表。您可以使用 list comprehension 而不是 for 循环将字符串列表转换为 int 列表,如下所示。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = [int(element) for element in myList]
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出:
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
这种方法在调用int()函数之前不检查字符串是否可以转换成 int。因此,如果我们在列表中发现一个不能转换成整数的元素,程序可能会遇到ValueError异常。您可以在下面的示例中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
new_list = [int(element) for element in myList]
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
new_list = [int(element) for element in myList]
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <listcomp>
new_list = [int(element) for element in myList]
ValueError: invalid literal for int() with base 10: 'Aditya'
在上面的例子中,字符串'Aditya'不能转换成 int。因此,程序会遇到 ValueError 异常。
异常导致程序突然终止。这可能会导致数据或程序中已完成的工作丢失。
为了处理异常,使程序不会突然终止,您可以使用如下所示的 python try-except 块。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
try:
new_list = [int(element) for element in myList]
print("The list of ints is:")
print(new_list)
except ValueError:
print("Some values in the input list can't be converted to int.")
输出:
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
Some values in the input list can't be converted to int.
使用 map()函数将字符串列表转换为整数
map() 函数用于使用一条 python 语句将函数应用于容器对象的所有元素。它将一个函数作为第一个输入参数,将一个容器对象作为第二个输入参数。执行后,它返回一个包含输出元素的 map 对象。
要将字符串列表转换为 int,我们将首先通过传递 int 函数作为第一个输入参数和字符串列表作为第二个参数来获得 map 对象。一旦我们获得了地图对象,我们将使用list()构造函数把它转换成一个列表。列表将包含整数形式的所有元素。您可以在下面的示例中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
new_list = list(map(int,myList))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出:
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21']
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
同样,这种方法在调用int()函数之前不检查字符串是否可以转换成 int。因此,如果我们在列表中发现一个不能转换成整数的元素,程序可能会遇到ValueError异常。您可以在下面的示例中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
new_list = list(map(int, myList))
print("The list of strings is:")
print(myList)
print("The list of ints is:")
print(new_list)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
new_list = list(map(int, myList))
ValueError: invalid literal for int() with base 10: 'Aditya'
为了处理异常,使程序不会突然终止,您可以使用 python try-except 块,如下所示。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
try:
new_list = list(map(int, myList))
print("The list of ints is:")
print(new_list)
except ValueError:
print("Some values in the input list couldn't be converted to int.")
输出:
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
Some values in the input list couldn't be converted to int.
使用 map()函数将字符串列表转换为整型
要使用 python 中的map()函数将字符串列表转换为整型,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储输出列表。 - 之后,我们将使用 for 循环遍历列表列表。
- 在迭代期间,我们将首先通过传递 int 函数作为其第一个输入参数和内部字符串列表作为其第二个参数来获得每个内部列表的 map 对象。
- 一旦我们获得了地图对象,我们将使用
list()构造函数把它转换成一个列表。 - 该列表将包含整数形式的内部列表的元素。我们将使用
append()方法把这个列表附加到new_list中。然后,我们将进入下一个内部列表。
在执行 for 循环后,我们将获得包含整数的列表列表作为内部列表的元素,如下面的代码所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
temp_list = list(map(int, inner_list))
new_list.append(temp_list)
print("The list of lists of ints is:")
print(new_list)
输出:
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
同样,在这种情况下,程序可能会运行到ValueError异常。因此,不要忘记在程序中使用 try-except 块,如下所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
try:
temp_list = list(map(int, inner_list))
new_list.append(temp_list)
except ValueError:
print("Some values couldn't be converted to int.")
print("The list of lists of ints is:")
print(new_list)
输出:
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21']]
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
使用 eval()函数将字符串列表转换为整数
eval() 函数用于解析和评估 python 语句。eval()函数将一个字符串作为其输入参数,解析该字符串,计算值,并返回输出。
例如,我们可以将字符串“2+2” 传递给 eval 函数,它将返回 4 作为输出。您可以在下面的示例中观察到这一点。
x = eval('2+2')
print(x)
输出:
4
类似地,当我们将一个只包含十进制数字的字符串传递给eval()函数时,它会返回一个整数,如下所示。
x = eval('11')
print(x)
输出:
11
如果输入字符串包含字母字符而不是数字,程序将运行到NameError异常。您可以在下面的示例中观察到这一点。
x = eval('Aditya')
print(x)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 1, in <module>
x = eval('Aditya')
File "<string>", line 1, in <module>
NameError: name 'Aditya' is not defined
这里,术语“Aditya”被评估为变量名。因此,eval()函数试图获取与变量“Aditya”关联的对象的值。但是,该程序不包含任何名为“Aditya”的变量。因此,程序遇到了一个NameError异常。
要使用eval() 函数将字符串列表转换为整数,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储整数。 - 之后,我们将使用 for 循环遍历字符串列表。
- 在迭代时,我们将首先检查当前字符串是否可以使用
isdigit()方法转换为 int。 - 如果字符串可以转换成 int,我们就用
eval()函数把字符串转换成 int。否则,我们会说当前字符串不能转换成整数。 - 在将字符串转换成 int 之后,我们将使用
append()方法将它附加到new_list中。 - 最后,我们将移动到输入列表中的下一个字符串。
在执行 for 循环后,我们将在new_list中获得 int 的列表。您可以在下面的示例中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
print("The list of strings is:")
print(myList)
new_list = []
for string in myList:
is_digit = string.isdigit()
if is_digit:
myInt = eval(string)
new_list.append(myInt)
else:
print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(new_list)
输出:
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
使用 eval()函数将字符串列表转换为整型
要使用eval()函数将字符串列表转换为整型,我们将使用以下步骤。
- 首先,我们将创建一个名为
new_list的空列表来存储列表的输出列表。 - 之后,我们将使用 for 循环遍历输入列表的内部列表。
- 在 for 循环中,我们将创建一个名为
temp_list的空列表来存储从内部列表中获得的 int 值。 - 然后,我们将使用另一个 for 循环迭代当前内部列表的元素。
- 在迭代内部列表的元素时,我们将首先检查当前字符串是否可以使用
isdigit()方法转换为 int。 - 如果字符串可以转换成 int,我们就用
eval()函数把字符串转换成 int。否则,我们会说当前字符串不能转换成整数。最后,我们将移动到当前内部列表中的下一个字符串。 - 在将当前内部列表的所有字符串转换成整数后,我们将使用
append()方法将它们附加到temp_list中。 - 迭代完每个内部循环后,我们将使用
append()方法将temp_list添加到new_list中。然后,我们将移动到列表列表中的下一个内部列表。
执行 for 循环后,我们将获得包含整数元素而不是字符串的列表,如下例所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
new_list = []
for inner_list in myList:
temp_list = []
for element in inner_list:
is_digit = element.isdigit()
if is_digit:
myInt = eval(element)
temp_list.append(myInt)
else:
print("'{}' cannot be converted into an integer.".format(element))
new_list.append(temp_list)
print("The list of lists of ints is:")
print(new_list)
输出:
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into an integer.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
在 Python 中将字符串列表就地转换为整型
前面几节中讨论的所有方法都创建了一个新的输出列表。如果我们想将输入列表的元素从 string 转换成 int,我们可以使用int()方法或eval()方法,而不是创建一个新的输出列表。
使用 int()函数将字符串列表就地转换为整数
要使用int()函数将字符串列表就地转换为整数,我们将使用以下步骤。
- 首先,我们将使用
len()函数找到字符串列表的长度。len()函数将列表作为其输入参数,并返回列表的长度。我们将把长度存储在变量list_len中。 - 获得列表长度后,我们将使用
range()函数创建一个从 0 到list_len的数字序列。range()函数将list_len作为输入参数,并返回序列。 - 获得序列后,我们将使用 for 循环遍历序列。迭代时,我们将使用索引来访问列表中的每个元素。
- 获得元素后,我们将检查它是否可以转换为整数。为此,我们将使用
isdigit()方法。 - 如果字符串可以转换成 int,我们就用
int()函数把字符串转换成 int。否则,我们会说当前字符串不能转换成整数。最后,我们将移动到当前内部列表中的下一个字符串。 - 在将当前内部列表的所有字符串转换成整数后,我们将把它们重新分配到它们在输入列表中的原始位置。
执行 for 循环后,输入列表的所有元素都将被转换为整数。您可以在下面的示例中观察到这一点。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
list_len = len(myList)
sequence = range(list_len)
print("The list of strings is:")
print(myList)
for index in sequence:
string = myList[index]
is_digit = string.isdigit()
if is_digit:
myInt = int(string)
myList[index] = myInt
else:
myList.remove(string)
print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(myList)
输出:
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
在上面的示例中,字符串“Aditya”不能转换为整数。因此,我们使用 remove()方法删除了字符串。
使用 eval()函数将字符串列表就地转换为整型
除了使用int()函数,您还可以使用eval()函数将字符串列表转换为 int,如下所示。
myList = ['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', "Aditya"]
list_len = len(myList)
sequence = range(list_len)
print("The list of strings is:")
print(myList)
for index in sequence:
string = myList[index]
is_digit = string.isdigit()
if is_digit:
myInt = eval(string)
myList[index] = myInt
else:
myList.remove(string)
print("'{}' cannot be converted into int.".format(string))
print("The list of ints is:")
print(myList)
输出:
The list of strings is:
['1', '2', '23', '32', '12', '44', '34', '55', '46', '21', 'Aditya']
'Aditya' cannot be converted into int.
The list of ints is:
[1, 2, 23, 32, 12, 44, 34, 55, 46, 21]
在 Python 中就地将字符串列表转换为整型
使用 int()函数将字符串列表转换为整数
我们还可以使用 int()函数将字符串列表就地转换成整型。为此,我们将使用以下步骤。
- 我们将使用 for 循环遍历列表的内部列表。
- 对于每个内部列表,我们将使用
len()函数找到字符串内部列表的长度。我们将把长度存储在变量list_len中。 - 获得内部列表的长度后,我们将使用
range()函数创建一个从 0 到list_len的数字序列。range()函数将list_len作为输入参数,并返回序列。 - 获得序列后,我们将使用 for 循环遍历序列。迭代时,我们将使用索引访问内部列表的每个元素。
- 获得元素后,我们将检查它是否可以转换为整数。为此,我们将使用
isdigit()方法。 - 如果字符串可以转换为 int,我们将使用
int()函数将字符串转换为 int。否则,我们会说当前字符串不能转换成整数。最后,我们将移动到当前内部列表中的下一个字符串。 - 在将当前内部列表的所有字符串转换成整数后,我们将把它们重新分配到它们在输入内部列表中的原始位置。
执行上述步骤后,原始列表的元素将被转换为整数。您可以在下面的示例中观察到这一点。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
for inner_list in myList:
list_len = len(inner_list)
sequence = range(list_len)
for index in sequence:
string = inner_list[index]
is_digit = string.isdigit()
if is_digit:
myInt = int(string)
inner_list[index] = myInt
else:
print("'{}' cannot be converted into int.".format(string))
inner_list.remove(string)
print("The list of lists of ints is:")
print(myList)
输出:
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into int.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
使用 eval()函数将字符串列表转换为整数
除了使用int()函数,你还可以使用eval()函数将字符串列表转换成整数,如下所示。
myList = [['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', "Aditya"]]
print("The list of lists of strings is:")
print(myList)
for inner_list in myList:
list_len = len(inner_list)
sequence = range(list_len)
for index in sequence:
string = inner_list[index]
is_digit = string.isdigit()
if is_digit:
myInt = eval(string)
inner_list[index] = myInt
else:
print("'{}' cannot be converted into int.".format(string))
inner_list.remove(string)
print("The list of lists of ints is:")
print(myList)
输出:
The list of lists of strings is:
[['1', '2', '23'], ['32', '12'], ['44', '34', '55', '46'], ['21', 'Aditya']]
'Aditya' cannot be converted into int.
The list of lists of ints is:
[[1, 2, 23], [32, 12], [44, 34, 55, 46], [21]]
结论
在本文中,我们讨论了在 python 中将字符串列表转换为整型的不同方法。如果需要将字符串列表转换成整数,可以使用使用map() 函数的方法。如果需要将字符串列表就地转换为 int,可以使用本文最后两节中讨论的方法。
我希望你喜欢阅读这篇文章。要了解更多关于 python 编程的知识,您可以阅读这篇关于如何在 Python 中删除列表中所有出现的字符的文章。您可能也喜欢这篇关于如何检查 python 字符串是否包含数字的文章。
快乐学习!
在 Python 中将列表转换为字符串
原文:https://www.pythonforbeginners.com/basics/convert-a-list-to-string-in-python
Python 字符串是最常用的数据类型之一。然而,Python 列表是最常用的数据结构。在本文中,我们将尝试使用 python 中的不同函数将列表转换为字符串。我们将使用 join()之类的字符串方法和 map()和 str()之类的函数将列表转换成字符串。
使用字符串串联将列表转换为字符串
在 python 中,将列表转换为字符串的最简单方法是使用 for 循环和字符串串联。要将列表转换为字符串,我们可以简单地将列表中的每个元素转换为字符串。然后我们可以把它们连接起来形成一个字符串。
为了执行转换,首先我们将获取一个空字符串。之后,我们将开始将列表中的每个元素转换成字符串后添加到空字符串中。在这个过程中,我们还会在每个元素之间添加空格。这可以如下进行。
myList = ["PFB", 11.2, 11, "Python"]
print("The List is:",myList)
myString = ""
for elem in myList:
myString = myString + str(elem) + " "
print("Output String is:")
print(myString.rstrip())
输出:
The List is: ['PFB', 11.2, 11, 'Python']
Output String is:
PFB 11.2 11 Python
在上面的例子中,我们可以看到在字符串的末尾添加了一个额外的空格。我们可以使用 rstrip()方法从字符串中删除多余的空格。
在 python 中将列表转换为字符串的另一种方法是使用 join()方法。join()方法用于从字符串列表中创建一个字符串。
join()方法在分隔符上调用,分隔符用于分隔字符串中的列表元素。字符串列表作为 join()方法的输入给出,它返回一个由列表元素创建的字符串。
我们将创建一个空字符串,列表中的所有元素都将连接到该字符串。为了创建字符串,我们将逐个获取列表中的每个元素,并将其转换为字符串。然后,我们将使用由列表的先前元素和当前元素组成的字符串创建一个字符串列表。我们将使用 join()方法从当前字符串和先前创建的字符串创建新字符串,方法是将一个空格字符作为分隔符,并对其调用 join()方法。我们将使用 for 循环对列表中的所有元素执行这个过程,直到形成完整的字符串。这可以从下面的例子中看出。
myList = ["PFB", 11.2, 11, "Python"]
print("The List is:", myList)
myString = ""
for elem in myList:
myString = " ".join([myString, str(elem)])
print("Output String is:")
print(myString.lstrip())
输出:
The List is: ['PFB', 11.2, 11, 'Python']
Output String is:
PFB 11.2 11 Python
在上面的方法中,在输出字符串的左侧添加了一个额外的空格,必须使用 lstrip()方法将其删除。为了避免这种情况,我们可以使用 map()函数将列表中的每个元素转换为一个字符串,而不是对列表中的每个元素应用 str()函数,这样我们就可以使用 join()方法执行字符串连接,从而使用一条语句获得输出字符串。
map()函数将一个函数和一个 iterable 作为输入参数,对 iterable 对象的每个元素执行该函数,并返回可以转换为列表的输出 map 对象。
为了将列表的元素转换成字符串,我们将把 str()函数和输入列表传递给 map()方法。之后,我们可以使用 join()方法从字符串列表中创建一个字符串,如下所示。
myList = ["PFB", 11.2, 11, "Python"]
print("The List is:", myList)
strList = list(map(str, myList))
myString = " ".join(strList)
print("Output String is:")
print(myString.lstrip())
输出:
The List is: ['PFB', 11.2, 11, 'Python']
Output String is:
PFB 11.2 11 Python
使用列表理解将列表转换为字符串
我们可以使用 list comprehension 将一个列表转换成一个字符串。为此,我们将使用 list comprehension 和 str()函数将列表中的每个元素转换为字符串,然后使用 join()方法将它们连接起来,如下所示。
myList = ["PFB", 11.2, 11, "Python"]
print("The List is:", myList)
strList = [str(i) for i in myList]
myString = " ".join(strList)
print("Output String is:", myString)
输出:
The List is: ['PFB', 11.2, 11, 'Python']
Output String is: PFB 11.2 11 Python
或者,我们可以使用 map()函数将列表中的元素转换为字符串。然后,我们将使用 list comprehension 从 map()函数创建的 map 对象创建一个新的列表,并将它作为 join()方法的输入,从列表创建一个字符串,如下所示。
myList = ["PFB", 11.2, 11, "Python"]
print("The List is:", myList)
myString = " ".join([i for i in map(str, myList)])
print("Output String is:", myString)
输出:
The List is: ['PFB', 11.2, 11, 'Python']
Output String is: PFB 11.2 11 Python
结论
在本文中,我们使用了 str()、map()和 join()函数将列表转换为字符串。我们也看到了如何使用列表理解来完成这项任务。要了解如何将字符串转换成列表,请阅读这篇关于 python 中的字符串拆分操作的文章。
在 Python 中将 CSV 转换为 HTML 表格
原文:https://www.pythonforbeginners.com/basics/convert-csv-to-html-table-in-python
CSV 文件包含逗号分隔的值,这些值通常包含表格。有时,我们可能需要将 csv 文件呈现为 HTML 页面。在本文中,我们将讨论如何用 python 将 csv 文件转换成 HTML 表格。
使用 pandas 模块将 CSV 转换为 HTML 表格
熊猫模块为我们提供了不同的工具来处理 csv 文件。要将 csv 文件转换成 HTML 表格,我们将首先使用read_csv()方法打开文件。read_csv()方法将 csv 文件的文件名作为输入参数,并返回包含来自 csv 文件的数据的 dataframe。
从 csv 文件获取数据到数据帧后,我们可以使用to_html()方法将数据帧转换成 HTML 字符串。在 dataframe 上调用to_html()方法时,会将 dataframe 转换为 HTML 表,并以字符串的形式返回 HTML 文本。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
html_string = df1.to_html()
print("The html string is:")
print(html_string)
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
The html string is:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Name</th>
<th>Roll Number</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>Aditya</td>
<td>12</td>
<td>Python</td>
</tr>
<tr>
<th>1</th>
<td>Sam</td>
<td>23</td>
<td>Java</td>
</tr>
<tr>
<th>2</th>
<td>Chris</td>
<td>11</td>
<td>C++</td>
</tr>
<tr>
<th>3</th>
<td>Joel</td>
<td>10</td>
<td>JavaScript</td>
</tr>
<tr>
<th>4</th>
<td>Mayank</td>
<td>5</td>
<td>Typescript</td>
</tr>
</tbody>
</table>
您也可以将数据直接保存到 HTML 文件中。为此,您必须将文件名作为输入参数传递给to_html()方法。在 dataframe 上调用to_html()方法时,该方法将 HTML 文件的文件名作为输入参数,并将其保存在当前工作目录中。在执行之后,to_html()方法在这种情况下返回 None。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
df1.to_html("html_output.html")
print("CSV file saved into html file.")
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
CSV file saved into html file.
下面是使用上述程序创建的 html 表格的快照。

使用 PrettyTable 模块将 CSV 转换为 HTML 表格
我们还可以使用PrettyTable()方法将 csv 文件转换成 HTML 文件。为此,我们将首先在读取模式下使用open()方法打开 csv 文件。open()方法将文件名作为第一个输入参数,将文字“r”作为第二个输入参数。执行后,它返回一个包含文件内容的 file 对象。
打开文件后,我们将使用readlines() 方法读取文件内容。在 file 对象上调用readlines()方法时,它将文件的内容作为字符串列表返回,其中列表的每个元素都包含输入文件中的一行。
现在,csv 文件的头将出现在由readlines() 方法返回的列表中的索引 0 处。我们将在由readlines()方法返回的列表的第一个元素上使用字符串分割操作提取 csv 文件的列名。
获得列表中的列名后,我们将使用PrettyTable()方法创建一个漂亮的表。PrettyTable()方法将包含列名的列表作为输入参数,并返回一个漂亮的表。创建表格后,我们将使用add_row()方法将数据添加到表格中。add_row()方法获取包含一行中的值的列表,并将其添加到 pretty 表中。
创建表格后,我们将使用get_html_string()方法获得表格的 HTML 字符串。当在 pretty table 对象上调用get_html_string()方法时,它以字符串的形式返回表格的 HTML 文本。
您可以在下面的示例中观察整个过程。
import prettytable
csv_file = open('student_details.csv', 'r')
data = csv_file.readlines()
column_names = data[0].split(',')
table = prettytable.PrettyTable()
table.add_row(column_names)
for i in range(1, len(data)):
row = data[i].split(",")
table.add_row(row)
html_string = table.get_html_string()
print("The html string obtained from the csv file is:")
print(html_string)
输出:
The html string obtained from the csv file is:
<table>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name</td>
<td>Roll Number</td>
<td> Subject<br></td>
</tr>
<tr>
<td>Aditya</td>
<td> 12</td>
<td> Python<br></td>
</tr>
<tr>
<td>Sam</td>
<td> 23</td>
<td> Java<br></td>
</tr>
<tr>
<td>Chris</td>
<td> 11</td>
<td> C++<br></td>
</tr>
<tr>
<td>Joel</td>
<td> 10</td>
<td> JavaScript<br></td>
</tr>
<tr>
<td>Mayank</td>
<td> 5</td>
<td> Typescript</td>
</tr>
</tbody>
</table>
结论
在本文中,我们讨论了如何用 python 将 csv 文件转换成 HTML 文件。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中列表理解的文章。你可能也会喜欢这篇关于用 python 理解字典的文章。
用 python 将 CSV 转换成 PDF 文件
原文:https://www.pythonforbeginners.com/basics/convert-csv-to-pdf-file-in-python
CSV 文件包含逗号分隔的值,这些值通常包含表格。有时,我们可能需要将 csv 文件转换成 PDF 文件。在本文中,我们将讨论如何用 python 将 csv 文件转换成 PDF。
如何用 Python 把 CSV 转换成 PDF 文件?
要将 csv 文件转换为 PDF,我们将首先使用 pandas 模块创建 csv 文件内容的 HTML 字符串。熊猫模块为我们提供了不同的工具来处理 csv 文件。
要将 csv 文件转换成 HTML 字符串,我们将首先使用read_csv()方法打开文件。read_csv()方法将 csv 文件的文件名作为输入参数,并返回包含来自 csv 文件的数据的 dataframe。
从 csv 文件获取数据到数据帧后,我们可以使用to_html()方法将数据帧转换成 HTML 字符串。在 dataframe 上调用to_html()方法时,会将 dataframe 转换为 HTML 表,并以字符串的形式返回 HTML 文本。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
html_string = df1.to_html()
print("The html string is:")
print(html_string)
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
The html string is:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Name</th>
<th>Roll Number</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>Aditya</td>
<td>12</td>
<td>Python</td>
</tr>
<tr>
<th>1</th>
<td>Sam</td>
<td>23</td>
<td>Java</td>
</tr>
<tr>
<th>2</th>
<td>Chris</td>
<td>11</td>
<td>C++</td>
</tr>
<tr>
<th>3</th>
<td>Joel</td>
<td>10</td>
<td>JavaScript</td>
</tr>
<tr>
<th>4</th>
<td>Mayank</td>
<td>5</td>
<td>Typescript</td>
</tr>
</tbody>
</table>
获得 HTML 字符串形式的 csv 文件后,我们将把 HTML 字符串转换成 pdf 文件。为此,我们将使用 pdfkit 模块,它构建在 wkhtmltopdf 库之上。pdfkit 模块为我们提供了from_string()方法,我们可以用它将 HTML 字符串转换成 pdf 文件。为此,我们将使用from_string()方法。from_string()方法将 HTML 字符串作为第一个输入参数,将 pdf 文件的文件名作为第二个输入参数。执行后,HMTL 字符串保存在 pdf 文件中。您可以在下面的示例中观察到这一点。
import pandas as pd
import pdfkit
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
html_string = df1.to_html()
pdfkit.from_string(html_string, "output_file.pdf")
print("PDF file saved.")
输出:
The dataframe is:
Name Roll Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
PDF file saved.
附件是从 csv 文件创建的 PDF 文件。
结论
在本文中,我们讨论了如何用 python 将 csv 文件转换成 pdf 文件。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中列表理解的文章。你可能也会喜欢这篇关于用 python 理解字典的文章。
在 Python 中将整数转换为字符串
原文:https://www.pythonforbeginners.com/basics/convert-integer-to-string-in-python
Python 字符串是为模式匹配等操作进行数据分析时最常用的数据类型之一。在本文中,我们将使用不同的方法在 python 中将整数转换成字符串。
使用 str()函数将整数转换为字符串
将整数转换为字符串的最简单方法是使用 str()函数。str()函数将整数作为输入,并返回其字符串表示形式,如下所示。
myInt = 1117
myStr = str(myInt)
print("The integer myInt is:", myInt)
print("The string myStr is:", myStr)
输出:
The integer myInt is: 1117
The string myStr is: 1117
我们可以检查输入变量和输出变量的类型,以确认整数是否已经转换为字符串。为此,我们将使用 type()函数。type 函数将 python 对象作为输入,并返回输入对象的数据类型,如下所示。
myInt = 1117
myStr = str(myInt)
print("The data type of myInt is:", type(myInt))
print("The data type of myStr is:", type(myStr))
输出:
The data type of myInt is: <class 'int'>
The data type of myStr is: <class 'str'>
使用字符串格式将整数转换为字符串
字符串格式化是一种将变量或另一个字符串插入预定义字符串的方法。我们也可以使用字符串格式将整数转换成字符串。在本文中,我们将使用“%s”操作符以及 format()方法将整数转换为字符串。
“%s”运算符用于格式化字符串中的值。一般用来避免字符串串联。但是,我们可以使用这个操作符将整数转换成字符串。为此,首先我们将创建一个空字符串,并在空字符串中放置一个%s 占位符。之后,我们可以指定需要转换成字符串的整数。在程序执行期间,python 解释器会将整数转换为字符串,如下例所示。
myInt = 1117
myStr = "%s" % myInt
print("myInt is:",myInt)
print("The data type of myInt is:", type(myInt))
print("myStr is:",myStr)
print("The data type of myStr is:", type(myStr))
输出:
myInt is: 1117
The data type of myInt is: <class 'int'>
myStr is: 1117
The data type of myStr is: <class 'str'>
代替“%s”操作符,我们也可以使用 format()方法来执行转换。为此,我们可以在空字符串中放置一个{}占位符。之后,我们可以在空字符串上调用 format 方法,将整数作为 format()方法的输入。这将把整数转换成字符串,如下所示。
myInt = 1117
myStr = "{}".format(myInt)
print("myInt is:",myInt)
print("The data type of myInt is:", type(myInt))
print("myStr is:",myStr)
print("The data type of myStr is:", type(myStr))
输出:
myInt is: 1117
The data type of myInt is: <class 'int'>
myStr is: 1117
The data type of myStr is: <class 'str'>
使用 F 弦进行转换
f 字符串用于将值或表达式嵌入到字符串中。我们也可以用 f 字符串把一个整数转换成一个字符串。
使用 f 字符串的语法类似于 format()方法的语法。唯一的区别是我们可以将变量直接放入占位符中。这使得代码更具可读性。要将整数变量 n 放入字符串,我们只需将 n 放入占位符{}中,如下所示。
f"This is a string containing {n}"
要使用 f 字符串将整数转换为字符串,我们将声明一个空字符串,其中只有一个整数占位符。这样,在运行时,整数将被转换为字符串。这可以从下面的例子中看出。
myInt = 1117
myStr = f"{myInt}"
print("myInt is:",myInt)
print("The data type of myInt is:", type(myInt))
print("myStr is:",myStr)
print("The data type of myStr is:", type(myStr))
输出:
myInt is: 1117
The data type of myInt is: <class 'int'>
myStr is: 1117
The data type of myStr is: <class 'str'>
结论
在本文中,我们看到了在 python 中将整数转换成字符串的不同方法。我们使用了内置的 str()方法、字符串格式以及 f 字符串。要了解更多关于字符串的内容,你可以阅读这篇关于 python 字符串拆分操作的文章。我们还可以使用 python try except 来编写本文中使用的程序,以使程序更加健壮,并以系统的方式处理错误。
用 Python 将列表转换成 CSV 文件
原文:https://www.pythonforbeginners.com/lists/convert-list-of-lists-to-csv-file-in-python
列表是 python 中最常用的数据结构之一。在本文中,我们将讨论如何用 python 将列表转换成 CSV 文件。
使用 csv.writer()将列表列表转换为 Python 中的 CSV
csv 模块为我们提供了对 CSV 文件执行各种操作的不同方法。要在 python 中将列表列表转换为 csv,我们可以使用 csv.writer()方法和 csv.writerow()方法。为此,我们将使用以下步骤。
- 首先,我们将使用 open()函数以写模式打开一个 csv 文件。open()函数将文件名作为第一个输入参数,将文字“w”作为第二个输入参数,以表明文件将以写模式打开。它返回一个 file 对象,该对象包含由 open()函数创建的空 csv 文件。
- 打开文件后,我们将使用 csv.writer()方法创建一个 csv.writer 对象。csv.writer()方法将 file 对象作为输入参数,并返回一个 writer 对象。一旦创建了 writer 对象,我们就可以使用 csv.writerow()方法将列表中的数据添加到 csv 文件中。
- 在 writer 对象上调用 csv.writerow()方法时,该方法获取一个值列表,并将其添加到 writer 对象引用的 csv 文件中。
- 首先,我们将为 CSV 文件添加文件头。为此,我们将把列名列表传递给 writerow()方法
- 添加头之后,我们将使用一个带有 writerow()方法的 for 循环将每个列表添加到 csv 文件中。这里,我们将把每个列表逐个传递给 writerow()方法。writerow()方法将列表添加到 csv 文件中。
执行 for 循环后,列表中的数据将被添加到 CSV 文件中。要保存数据,应该使用 close()方法关闭文件。否则,不会将任何更改保存到 csv 文件中。
使用 csv.writer()方法将列表转换为 csv 文件的源代码如下。
import csv
listOfLists = [["Aditya", 1, "Python"], ["Sam", 2, 'Java'], ['Chris', 3, 'C++'], ['Joel', 4, 'TypeScript']]
print("THe list of lists is:")
print(listOfLists)
myFile = open('demo_file.csv', 'w')
writer = csv.writer(myFile)
writer.writerow(['Name', 'Roll', 'Language'])
for data_list in listOfLists:
writer.writerow(data_list)
myFile.close()
myFile = open('demo_file.csv', 'r')
print("The content of the csv file is:")
print(myFile.read())
myFile.close()
输出:
THe list of lists is:
[['Aditya', 1, 'Python'], ['Sam', 2, 'Java'], ['Chris', 3, 'C++'], ['Joel', 4, 'TypeScript']]
The content of the csv file is:
Name,Roll,Language
Aditya,1,Python
Sam,2,Java
Chris,3,C++
Joel,4,TypeScript
结论
在本文中,我们讨论了一种用 python 将列表转换成 csv 文件的方法。在这些方法中,每个列表都将被添加到 csv 文件中,而不管它与 csv 中的列相比是否具有相同数量的元素。因此,建议确保每个元素都有相同数量的元素。此外,您应该确保列表中元素的顺序应该相同。否则,附加到 csv 文件的数据将变得不一致,并会导致错误。
要了解更多关于 python 中的列表,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
在 Python 中将字符串转换为日期时间
原文:https://www.pythonforbeginners.com/basics/convert-string-to-datetime-in-python
我们通常将日期以字符串的形式保存在文本文件或电子表格中。在 python 中处理日期和时间时,我们经常需要计算两个事件之间花费的天数或时间。在这样的计算中,我们可以使用 python datetime 模块,在它的帮助下,我们可以将日期存储为 python 对象。在本文中,我们将讨论如何在 python 中将字符串转换为日期时间对象。
Python 中的 Datetime 是什么?
Python 为我们提供了datetime模块来处理与时间和日期相关的数据。它定义了许多函数来计算当前时间,两个日期之间花费的时间等等。例如,您可以使用下面的datetime.now()函数获得当前日期和时间。
import datetime
today = datetime.datetime.now()
print("The Current Date and Time is:", today)
输出:
The Current Date and Time is: 2021-11-22 22:34:25.828339
datetime.now()函数的输出是一个 datetime 对象,它有许多属性,如year、month、day、minute、second和microsecond。您可以按如下方式访问每个属性。
import datetime
today = datetime.datetime.now()
print("The Current Year is:", today.year)
print("The Current Month is:", today.month)
print("The Current Day is:", today.day)
print("The Current Hour is:", today.hour)
print("The Current Minute is:", today.minute)
print("The Current Second is:", today.second)
print("The Current Microsecond is:", today.microsecond)
输出:
The Current Year is: 2021
The Current Month is: 11
The Current Day is: 22
The Current Hour is: 22
The Current Minute is: 36
The Current Second is: 30
The Current Microsecond is: 972280
我们还可以使用datetime()构造函数创建一个 datetime 对象。它接受年、月和日作为其第一、第二和第三个参数,并返回一个 datetime 对象,如下所示。
import datetime
day = datetime.datetime(1999, 1, 20)
print("The Date is:", day)
输出:
The Date is: 1999-01-20 00:00:00
您还可以将小时、分钟、秒、微秒和时区参数传递给datetime()构造函数,作为 day 之后的后续参数,顺序相同。这些是可选参数,小时、分钟、秒和微秒的默认值为 0。时区的默认值为无。
Python 中如何把字符串转换成 Datetime?
除了直接创建日期对象,我们还可以在 python 中将字符串转换为日期时间对象。我们可以使用datetime.strptime()方法来实现。
datetime.strptime()方法接受一个包含日期的字符串作为第一个输入参数,一个包含日期格式的字符串作为第二个输入参数。执行后,它返回一个 datetime 对象,如下所示。
import datetime
input_string = "1999-01-20"
print("The input string is:",input_string)
date_format = "%Y-%m-%d" # %Y for year, %m for month and %d for day
day = datetime.datetime.strptime(input_string, date_format)
print("The Date is:", day)
输出:
The input string is: 1999-01-20
The Date is: 1999-01-20 00:00:00
我们还可以为输入字符串指定其他格式,并将它们转换为 datetime 对象,如下例所示。
import datetime
input_string = "1999/01/20"
print("The input string is:",input_string)
date_format = "%Y/%m/%d" # %Y for year, %m for month and %d for day
day = datetime.datetime.strptime(input_string, date_format)
print("The Date is:", day)
input_string = "20-01-1999"
print("The input string is:",input_string)
date_format = "%d-%m-%Y" # %Y for year, %m for month and %d for day
day = datetime.datetime.strptime(input_string, date_format)
print("The Date is:", day)
input_string = "20/01/1999"
print("The input string is:",input_string)
date_format = "%d/%m/%Y" # %Y for year, %m for month and %d for day
day = datetime.datetime.strptime(input_string, date_format)
print("The Date is:", day)
输出:
The input string is: 1999/01/20
The Date is: 1999-01-20 00:00:00
The input string is: 20-01-1999
The Date is: 1999-01-20 00:00:00
The input string is: 20/01/1999
The Date is: 1999-01-20 00:00:00
结论
在本文中,我们讨论了 python 中的 datetime 对象。我们还讨论了如何在 python 中将字符串转换成日期时间对象。要了解更多关于字符串的知识,可以阅读这篇关于 python 中的字符串方法的文章。您可能也会喜欢这篇关于 python 中的字符串连接的文章。
在 Python 中将字符串转换为列表
原文:https://www.pythonforbeginners.com/basics/convert-string-to-list-in-python
字符串和列表是最常用的 python 对象。有时,在操作字符串时,我们需要将字符串转换成列表。在本文中,我们将讨论在 Python 中将字符串转换成列表的不同方法。
使用 Python 中的 List()函数将字符串转换为列表
list()函数用于从现有的 iterable 对象创建一个列表。list()函数将一个 iterable 对象作为它的输入参数。执行后,它返回一个包含 iterable 对象所有元素的列表。
为了在 Python 中将字符串转换成列表,我们将把输入字符串传递给 list()函数。执行后,它将返回一个包含输入字符串字符的列表。您可以在下面的示例中观察到这一点。
myStr = "pythonforbeginners"
output_list = list(myStr)
print("The input string is:", myStr)
print("The output list is:", output_list)
输出:
The input string is: pythonforbeginners
The output list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
在上面的例子中,我们已经将字符串pythonforbeginners传递给了list()函数。执行后,它返回字符串中的字符列表。
Python 中使用 append()方法列出的字符串
方法用于将一个元素添加到一个列表中。当在列表上调用时,它将一个元素作为其输入参数,并将该元素追加到列表中。
要使用append()方法将字符串转换成列表,我们将使用以下步骤。
- 首先,我们将创建一个名为
myList的空列表来存储输出列表。 - 之后,我们将使用 for 循环遍历输入字符串的字符。
- 在迭代过程中,我们将使用
append()方法将当前字符添加到myList中。
执行 for 循环后,我们将在myList中得到输出列表。您可以在下面的示例中观察到这一点。
myStr = "pythonforbeginners"
myList = []
for character in myStr:
myList.append(character)
print("The input string is:", myStr)
print("The output list is:", myList)
输出:
The input string is: pythonforbeginners
The output list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
在这里,您可以观察到我们使用 for 循环和append()方法从输入字符串中获得了一个列表。
使用 Python 中的 extend()方法列出的字符串
方法用来同时向一个列表中添加几个元素。当在列表上调用时,extend() 方法将 iterable 对象作为其输入参数。执行后,它将 iterable 对象的所有元素追加到列表中。
为了使用extend()方法将字符串转换成列表,我们将首先创建一个名为myList的空列表。之后,我们将调用myList上的extend() 方法,并将输入字符串作为extend()方法的输入参数。
在执行了extend()方法之后,我们将在myList中得到结果输出。您可以在下面的示例中观察到这一点。
myStr = "pythonforbeginners"
myList = []
myList.extend(myStr)
print("The input string is:", myStr)
print("The output list is:", myList)
输出:
The input string is: pythonforbeginners
The output list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
在上面的例子中,我们使用 extend()方法获得了字符串的字符列表。
使用 Python 中的列表理解将字符串转换为列表
列表理解用于从现有的可迭代对象创建一个新列表。理解列表的语法如下。
newList=[expression for element in iterable]
为了在 python 中将字符串转换成列表,我们将使用输入字符串来代替iterable。在expression和element的位置,我们将使用字符串的字符。
执行上述语句后,我们将在newList中得到输出列表。
您可以在下面的示例中观察到这一点。
myStr = "pythonforbeginners"
myList = [character for character in myStr]
print("The input string is:", myStr)
print("The output list is:", myList)
输出:
The input string is: pythonforbeginners
The output list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
结论
在本文中,我们讨论了在 Python 中将字符串转换为列表的四种方法。在所有这些方法中,您可以使用list()函数从输入字符串创建一个新的列表。
如果您想将字符串中的字符添加到现有的列表中,您可以使用带有append() 方法或extend()方法的方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于 Python 中的字符串连接的文章。你可能也会喜欢这篇关于用 Python 理解字典的文章。
请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中将字符串转换为集合
原文:https://www.pythonforbeginners.com/basics/convert-string-to-set-in-python
在 python 中,字符串用于操作文本数据。有时,我们可能需要找出文本中不同字符的总数。在这种情况下,我们可以将字符串转换成集合。在本文中,我们将讨论在 python 中将字符串转换为集合的不同方法。
使用 Set()函数在 Python 中将字符串转换为集合
set()函数用于在 Python 中创建一个集合。它将一个 iterable 对象作为其输入参数,并返回一个包含 iterable 对象中元素的集合。
正如我们所知,字符串是一个可迭代的对象,我们可以使用set()函数从 python 中的字符串获得一个集合。为此,我们将把字符串作为输入参数传递给set()函数。执行set()函数后,我们将得到输入字符串的所有字符的集合。您可以在下面的示例中观察到这一点。
myStr = "pythonforbeginners"
mySet = set(myStr)
print("The input string is:", myStr)
print("The output set is:", mySet)
输出:
The input string is: pythonforbeginners
The output set is: {'f', 'i', 'g', 'y', 'o', 'r', 't', 'h', 'p', 'n', 'b', 'e', 's'}
在上面的例子中,您可以观察到我们将字符串pythonforbeginners作为输入传递给了set()函数。执行后,它返回一个包含字符串中字符的集合。
使用集合理解在 Python 中将字符串转换为集合
集合理解用于从现有的可迭代对象创建新的集合。集合理解的语法如下。
newSet= { expression for element in iterable }
为了使用 Python 中的集合理解将字符串转换成集合,我们将使用输入字符串作为iterable,将字符串的字符作为element以及expression。执行后,上述语句会将字符串转换为 set。您可以在下面的示例中观察到这一点。
myStr = "pythonforbeginners"
mySet = {character for character in myStr}
print("The input string is:", myStr)
print("The output set is:", mySet)
输出:
The input string is: pythonforbeginners
The output set is: {'i', 'n', 'o', 's', 't', 'h', 'b', 'g', 'e', 'r', 'p', 'y', 'f'}
在上面的例子中,我们已经使用 set comprehension 将pythonforbeginners转换为 Python 中的集合。
使用 add()方法在 Python 中设置的字符串
add()方法用于向集合中添加一个元素。当在集合上调用时,add()方法将一个元素作为它的输入参数。执行后,如果元素不存在于集合中,它会将该元素添加到集合中。如果元素已经存在于集合中,则什么也不会发生。
要使用 python 中的add()方法将字符串转换为集合,我们将使用以下步骤。
- 首先,我们将创建一个名为
mySet的空集。为此,我们将使用set()函数。set()函数在不带任何参数的情况下执行时,返回一个空集。 - 创建空集后,我们将使用 for 循环遍历输入字符串的字符。
- 在迭代过程中,我们将调用
mySet上的add()方法,并将每个字符添加到mySet。 - 在执行 for 循环后,我们将获得变量
mySet中设置的输出。您可以在下面的示例中观察到这一点。
myStr = "pythonforbeginners"
mySet = set()
for character in myStr:
mySet.add(character)
print("The input string is:", myStr)
print("The output set is:", mySet)
输出:
The input string is: pythonforbeginners
The output set is: {'h', 'n', 'g', 'f', 'i', 'b', 'o', 'p', 't', 'e', 's', 'r', 'y'}
在这个例子中,我们使用了add()方法将字符串 pythonforbeginners 转换为一个集合。
结论
在本文中,我们讨论了在 Python 中将字符串转换为集合的三种方法。在所有这三种方法中,如果您需要在集合中包含字符串的所有字符,您可以使用使用set(函数的方法。
如果您需要从集合中排除输入字符串的某些字符,您可以使用带有add()方法或集合理解的方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的字符串连接的文章。你可能也会喜欢这篇关于 Python 中字典理解的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中将字符串转换为变量名
原文:https://www.pythonforbeginners.com/basics/convert-string-to-variable-name-in-python
在用 python 编程时,有几种情况下我们可能需要将字符串转换成变量名。例如,假设我们需要将一些用户数据作为输入,用户需要输入一些字段名称和它们相应的值。我们需要将字段名转换成一个变量,这样我们就可以给它们赋值。在本文中,我们将讨论在 python 中将输入字符串转换为变量名的不同方法。
Python 中的字符串和变量
myVar = 5
print("The value in myVar is:", myVar)
输出:
The value in myVar is: 5
python 字符串是包含在单引号或双引号中的文字。我们也可以使用三重引号来定义字符串。我们可以定义一个字符串值,并将其赋给一个字符串变量,如下例所示。
myStr = "PythonForBeginners"
print("The value in myStr is:", myStr)
输出:
The value in myStr is: PythonForBeginners
在上面的例子中,我们创建了一个变量myStr。然后,我们将字符串“PythonForBeginners”赋给了myStr。
如何在 Python 中访问变量名?
我们可以使用globals()函数和locals()函数来访问 python 中的变量名。
执行时,globals()函数返回一个字典,其中包含所有字符串形式的变量名及其对应的值。它是一个全局符号表,包含程序全局范围内定义的所有名称。您可以在下面的 python 代码中观察到这一点。
myStr = "PythonForBeginners"
myNum = 5
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
输出:
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fe3bfa934c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
在上面的例子中,您可以观察到由globals()函数返回的字典包含一些默认值以及我们定义的变量。
globals()函数返回只包含全局变量作为键的字典。当我们在函数或其他内部作用域中定义一个变量时,我们不能使用globals()函数访问在该作用域中定义的变量。例如,看看下面的代码。
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
myStr = "PythonForBeginners"
myNum = 5
myFun()
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
输出:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f9d18bb24c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7f9d18b6f280>, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
Process finished with exit code 0
在上面的例子中,我们已经在函数 myFun 中定义了 funvar1 和 funvar2。然而,这些变量不存在于全局符号表中。
即使我们执行函数myFun中的globals()函数,在myFun中定义的变量也不会包含在全局符号表中。您可以在下面的示例中观察到这一点。
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
print("The variables in global scope and their values are:")
myVars = globals()
print(myVars)
myStr = "PythonForBeginners"
myNum = 5
myFun()
输出:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7eff3f70d4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7eff3f6ca280>, 'myStr': 'PythonForBeginners', 'myNum': 5}
要打印函数中定义的变量名,我们可以使用 locals() 函数。
当在函数或其他内部作用域中调用时,locals()函数返回一个字典,其中变量名及其相关值作为一个键-值对出现。
您可以使用 print 语句来打印字典,如下所示。
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
print("The variables in local scope of myFun and their values are:")
myVars = locals()
print(myVars)
myStr = "PythonForBeginners"
myNum = 5
myFun()
输出:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in local scope of myFun and their values are:
{'funvar1': 'Aditya', 'funVar2': 1117}
在上面的例子中,您可以观察到由locals()函数返回的字典包含了在myFun内部定义的变量。
locals()函数在全局范围内执行时,打印包含全局变量及其值的字典。您可以在下面的示例中观察到这一点。
def myFun():
funvar1 = "Aditya"
funVar2 = 1117
print("I am in myFun. The variables in myFun are:")
print(funvar1, funVar2)
myStr = "PythonForBeginners"
myNum = 5
myFun()
print("The variables in the global scope and their values are:")
myVars = locals()
print(myVars)
输出:
I am in myFun. The variables in myFun are:
Aditya 1117
The variables in the global scope and their values are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fd4fec2e4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myFun': <function myFun at 0x7fd4febeb280>, 'myStr': 'PythonForBeginners', 'myNum': 5, 'myVars': {...}}
既然我们已经讨论了如何在 python 中访问变量名,现在让我们讨论如何在 python 中创建动态变量和定义动态变量名。对于这一点,有各种方法,我们将逐一讨论。
使用 locals()方法将字符串转换为 Python 中的变量名
正如我们在上一节中看到的,python 解释器将变量名和它们的值以字典的形式存储在一个符号表中。如果在我们的程序中给我们一个字符串作为输入,我们可以通过将输入字符串作为一个键添加到符号表中,用该字符串定义一个变量名。我们可以添加单个字符、数值或字符串作为变量的关联值。
要将字符串转换为变量名,我们将遵循以下步骤。
- 首先,我们将使用
locals()函数获得包含符号表的字典。locals()函数在执行时返回当前作用域的符号表。 - 一旦我们获得了符号表,我们将使用下标符号添加字符串名称作为键,变量的值作为关联值。
- 将键-值对添加到符号表后,将使用给定的字符串名称和关联的值创建变量。
您可以通过这个简单的例子观察到这一点。
myStr = "domain"
print("The string is:",myStr)
myVars = locals()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
输出:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f2fb9cb44c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
在上面的例子中,我们使用了下标符号对符号表进行了修改。您可以使用__setitem__() 方法,而不是使用下标符号将新的字符串值作为键添加到符号表中。
当在 python 字典上调用 __setitem__()方法时,该方法将一个字符串文字作为第一个参数,并将与新变量名相关联的值作为第二个参数。执行后,字符串和值作为字典中的键-值对添加到字典中。
由于locals()方法返回的符号表也是一个字典,我们可以使用__setitem__() 方法将字符串转换成 python 中的变量名,如下所示。
myStr = "domain"
print("The string is:", myStr)
myVars = locals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
输出:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f77830734c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
上面使用locals()方法的方法只在当前作用域中进行修改,因此,当我们想把一个字符串转换成一个像函数一样的局部作用域中的变量名时,这是很有用的。如果你只想改变一个函数的符号表,可以使用locals() 函数将一个字符串转换成 python 中的变量名,如下所示。
def myFun():
myStr = "domain"
print("The string is:", myStr)
myVars = locals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
myFun()
输出:
The string is: domain
The variables are:
{'myStr': 'domain', 'domain': 'pythonforbeginners.com'}
如果您想在全局符号表中进行更改,将一个 python 字符串转换成一个全局变量名,您可以在全局范围内执行locals()函数。之后,您可以使用下标符号或前面示例中所示的__setitem__()方法添加变量。
使用 globals()方法将字符串转换为 Python 中的变量名
如果你想在函数中把一个字符串转换成一个全局变量,你不能使用locals()函数。对于此任务,您可以使用globals()功能。
执行时,globals()函数返回全局符号表。您可以在任何范围内对全局符号表进行更改,以将字符串转换为全局变量名。为此,我们将执行以下步骤。
- 首先,我们将使用
globals()函数获得全局符号表。globals()函数在执行时,将全局符号表作为字典返回。 - 一旦我们获得了符号表,我们将使用字典的下标符号添加字符串名称作为键,变量值作为关联值。
- 将键-值对添加到符号表后,将使用给定的字符串名称和关联的值创建变量。
执行以上步骤后,我们可以将一个字符串转换成一个全局变量。您可以在下面的示例中观察到这一点。
myStr = "domain"
print("The string is:",myStr)
myVars = globals()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
输出:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7ff717bd34c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
不使用下标符号,您可以使用带有globals()函数的__setitem__()方法将字符串转换成 python 中的全局变量名,如下所示。
myStr = "domain"
print("The string is:", myStr)
myVars = globals()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
输出:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fc4c62ba4c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
使用 vars()函数将字符串转换成 Python 中的变量名
在 python 中,除了使用locals() 和globals()函数将字符串转换为变量名,我们还可以使用 vars()函数。当在全局范围内执行时,vars()函数的行为就像globals()函数一样。当在函数或内部作用域中执行时,vars()函数的行为类似于locals() 函数。
要在全局范围内使用vars()函数将字符串转换成变量名,我们将使用以下步骤。
- 使用
vars()函数,我们将获得包含全局范围内变量名的字典。 - 获得字典后,我们将使用字典的下标符号添加字符串名称作为键,变量的值作为关联值。
- 一旦我们将字符串和相关值添加到字典中,就在全局范围内创建了变量。
下面是在 python 中执行上述步骤将字符串转换为变量名的示例代码。
myStr = "domain"
print("The string is:",myStr)
myVars = vars()
myVars[myStr] = "pythonforbeginners.com"
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
输出:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb9c6d614c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
您也可以使用字典上的__setitem__()方法而不是下标符号来创建变量,如下例所示。
myStr = "domain"
print("The string is:", myStr)
myVars = vars()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
print("{} is {}".format(myStr, domain))
输出:
The string is: domain
The variables are:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb5e21444c0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/aditya1117/PycharmProjects/pythonProject/string12.py', '__cached__': None, 'myStr': 'domain', 'myVars': {...}, 'domain': 'pythonforbeginners.com'}
domain is pythonforbeginners.com
要使用vars()函数将字符串转换为局部范围内的变量名,就像函数一样,您可以执行与我们使用locals()函数创建全局变量相同的步骤。您可以在下面的示例中观察到这一点。
def myFun():
myStr = "domain"
print("The string is:", myStr)
myVars = vars()
myVars.__setitem__(myStr, "pythonforbeginners.com")
print("The variables are:")
print(myVars)
myFun()
输出:
The string is: domain
The variables are:
{'myStr': 'domain', 'domain': 'pythonforbeginners.com'}
在前面的章节中,我们已经直接更改了符号表,将字符串转换为变量名。但是,这不是执行任务的最佳方式。
现在让我们讨论如何在不直接改变符号表的情况下,在 python 中将字符串转换为变量名。
使用 exec()函数将字符串转换成 Python 中的变量名
我们可以使用 exec()函数来动态执行 python 语句。exec()函数将字符串形式的 python 语句作为输入参数。然后,执行 python 语句,就像它是用代码编写的普通 python 语句一样。例如,我们可以使用如下所示的exec()函数定义一个值为 5 的变量 x。
myStr = "x=5"
exec(myStr)
print(x)
输出:
5
要使用 exec()函数将字符串转换为变量名,我们将使用字符串格式。我们可以使用以下步骤来完成整个过程。
- 首先,我们将定义一个变量 myStr,它包含我们需要转换成变量名的原始字符串。
- 之后,我们将创建一个格式为"
{} ="{}""的字符串myTemplate。这里,我们将使用第一个占位符表示字符串名称,第二个占位符表示我们将从字符串变量创建的变量值。 - 在创建了带有占位符的字符串之后,我们将调用
myTemplate上的format()方法,将myStr作为第一个输入参数,将从myStr创建的变量的值作为第二个输入参数。 - 一旦执行,
format()方法将返回一个类似 python 语句的字符串,并将myStr作为变量名,给定的值被赋给它。 - 在获得包含 python 语句的字符串后,我们将把它传递给
exec()函数。 - 一旦执行了
exec()函数,就会创建一个以字符串myStr作为变量名的变量。
您可以在下面的示例中观察到这一点。
myStr = "domain"
myVal = "pythonforbeginners.com"
myTemplate = "{} = \"{}\""
statement = myTemplate.format(myStr, myVal)
exec(statement)
print(domain)
输出:
pythonforbeginners.com
使用 setattr()函数将字符串转换成 Python 中的变量名
除了使用 exec()函数,我们还可以使用setattr()函数将字符串转换成 python 中的变量名。
setattr()函数将 python 对象作为第一个输入参数,将属性(变量)名称作为第二个输入参数,将属性值作为第三个输入参数。执行后,它将属性添加到对象中。
要使用setattr()函数将字符串转换为变量名,我们首先需要获得 python 对象的当前作用域,这样我们就可以将变量作为属性添加到其中。为此,我们必须执行两项任务。
- 首先,我们需要获得程序中当前加载的模块的名称。
- 之后,我们需要找到当前正在执行的模块,即当前作用域。
为了找到当前加载到内存中的模块的名称,我们将使用sys.modules属性。属性包含一个字典,该字典将模块名映射到已经加载的模块。
获得字典后,我们需要找到当前模块。为此,我们将使用__name__属性。__name__是一个内置属性,计算结果为当前模块的名称。
__name__属性也出现在符号表中。您可以使用如下所示的__name__属性找到当前模块的名称。
print("The current module name is:")
print(__name__)
输出:
The current module name is:
__main__
在这里,您可以看到我们目前处于__main__模块。
在使用__name__属性获得当前模块的名称之后,我们将使用sys.modules属性上的下标符号获得当前模块对象。
获得当前模块后,我们将使用setattr()函数将字符串转换为变量名。为此,我们将当前模块作为第一个输入参数,字符串作为第二个输入参数,变量的值作为第三个输入参数传递给setattr()函数。执行完 setattr()函数后,将在当前范围内创建变量,输入字符串作为变量名。
您可以在下面的示例中观察到这一点。
import sys
myStr = "domain"
myVal = "pythonforbeginners.com"
moduleName = __name__
currModule = sys.modules[moduleName]
setattr(currModule, myStr,myVal)
print(domain)
输出:
pythonforbeginners.com
结论
在本文中,我们讨论了在 python 中将字符串转换为变量名的不同方法。在本文讨论的所有方法中,我建议您使用带有 exec()方法的方法。这是因为有几个保留的关键字不能用作变量名。关键字用于运行程序的不同任务。然而,如果我们直接改变符号表,我们可能会改变与关键字相关的值。在这种情况下,程序会出错。因此,尝试使用带有 exec() 函数的方法来将字符串转换成 python 中的变量名。
在 Python 中将元组转换为字符串
原文:https://www.pythonforbeginners.com/strings/convert-tuple-to-string-in-python
在 python 中,一个元组可以包含不同的元素。另一方面,字符串只是一系列字符。在本文中,我们将讨论在 python 中给定一组字符时,如何将元组转换为字符串。
如何将字符元组转换成字符串?
假设我们有下面的字符组。
myTuple = ("P", "y", "t", "h", "o", "n")
现在,我们必须将这个元组转换成字符串“Python”。
为了将 tuple 转换成 string,我们将首先创建一个名为output_string的空字符串。之后,我们将使用 for 循环遍历元组。遍历时,我们将使用字符串串联操作将元组中的每个字符添加到output_string中。在执行 for 循环后,我们将在变量output_string中获得所需的字符串。您可以在下面的示例中观察到这一点。
myTuple = ("P", "y", "t", "h", "o", "n")
output_string = ""
for character in myTuple:
output_string += character
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
输出:
The input tuple is: ('P', 'y', 't', 'h', 'o', 'n')
The output string is: Python
不使用 for 循环,我们可以使用join()方法将字符元组转换成字符串。在字符串上调用join()方法时,该方法将包含字符串的 iterable 对象作为输入参数。执行后,它返回包含新字符的修改后的字符串以及原始字符串中的字符。
为了将一组字符转换成一个字符串,我们将首先创建一个名为output_string的空字符串。之后,我们将调用output_string上的 join() 方法,并将元组作为输入参数。执行后, join()方法将返回所需的字符串,如下所示。
myTuple = ("P", "y", "t", "h", "o", "n")
output_string = ""
output_string = output_string.join(myTuple)
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
输出:
The input tuple is: ('P', 'y', 't', 'h', 'o', 'n')
The output string is: Python
将数字元组转换为字符串
如果你试图用上面讨论的任何一种方法将一组数字转换成一个字符串,程序将会抛出TypeError异常。您可以在下面的示例中观察到这一点。
myTuple = (1, 2, 3, 4, 5, 6)
output_string = ""
for character in myTuple:
output_string += character
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 4, in <module>
output_string += character
TypeError: can only concatenate str (not "int") to str
类似地,当我们使用第二种方法时,程序会遇到如下所示的TypeError异常。
myTuple = (1, 2, 3, 4, 5, 6)
output_string = ""
output_string = output_string.join(myTuple)
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 3, in <module>
output_string = output_string.join(myTuple)
TypeError: sequence item 0: expected str instance, int found
为了避免错误,我们只需在将元组添加到output_string之前将它的每个元素转换成一个字符串。在第一种方法中,我们将首先使用str()函数将元组的每个元素转换成一个字符串。之后,我们将执行连接操作。这样,我们可以将一组数字转换成一个字符串。
myTuple = (1, 2, 3, 4, 5, 6)
output_string = ""
for element in myTuple:
character = str(element)
output_string += character
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
输出:
The input tuple is: (1, 2, 3, 4, 5, 6)
The output string is: 123456
对于使用join()方法的方法,我们将首先把数字元组转换成字符串元组。为此,我们将使用map()函数和str()函数。
map()函数将一个函数作为第一个参数,将一个 iterable 对象作为第二个输入参数。执行后,它返回一个 map 对象,其中函数应用于 iterable 对象的每个元素。我们将把str()函数和数字元组作为输入参数传递给map()函数。之后,我们将使用tuple()构造函数转换地图对象。因此,我们将得到一个字符串元组,如下所示。
myTuple = (1, 2, 3, 4, 5, 6)
newTuple = tuple(map(str, myTuple))
print("The input tuple is:", myTuple)
print("The output tuple is:", newTuple)
输出:
The input tuple is: (1, 2, 3, 4, 5, 6)
The output tuple is: ('1', '2', '3', '4', '5', '6')
从数字元组得到字符串元组后,我们可以直接得到字符串如下。
myTuple = (1, 2, 3, 4, 5, 6)
newTuple = tuple(map(str, myTuple))
output_string = ''.join(newTuple)
print("The input tuple is:", myTuple)
print("The output string is:", output_string)
输出:
The input tuple is: (1, 2, 3, 4, 5, 6)
The output string is: 123456
结论
在本文中,我们讨论了如何在 python 中将元组转换为字符串。要了解 python 中字符串的更多信息,可以阅读这篇关于 python 中字符串格式化的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
用 Python 复制列表
原文:https://www.pythonforbeginners.com/basics/copy-a-list-in-python
在用 python 编程时,我们有时需要在多个地方存储相同的数据。这可能是因为我们需要保存原始数据。在本文中,我们将讨论在 python 中复制列表的不同方法。
用 Python 复制列表
当我们需要在 python 中复制一个整数时,我们只需将一个变量赋给另一个变量,如下所示。
num1 = 10
print("The first number is:", num1)
num2 = num1
print("The copied number is:", num2)
输出:
The first number is: 10
The copied number is: 10
这里,我们创建了一个值为 10 的变量num1。然后,我们将num1赋给另一个变量num2。赋值后,即使我们改变了原始变量,复制变量中的值仍然不受影响。您可以在下面的示例中观察到这一点。
num1 = 10
print("The first number is:", num1)
num2 = num1
print("The copied number is:", num2)
num1 = 15
print("The first number after modification:", num1)
print("The copied number is:", num2)
输出:
The first number is: 10
The copied number is: 10
The first number after modification: 15
The copied number is: 10
在上面的例子中,你可以看到在修改了num1之后num2中的值并没有被修改。
现在,让我们使用赋值操作复制一个列表。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", list1)
list2 = list1
print("The copied list is:", list2)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The copied list is: [1, 2, 3, 4, 5, 6, 7]
在这种情况下,当我们更改原始列表时,复制的列表也会被修改。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", list1)
list2 = list1
print("The copied list is:", list2)
list1.append(23)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list2)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The copied list is: [1, 2, 3, 4, 5, 6, 7]
The original list after modification is: [1, 2, 3, 4, 5, 6, 7, 23]
The copied list after modification is: [1, 2, 3, 4, 5, 6, 7, 23]
为什么会这样?
通过赋值复制适用于整数,因为整数是不可变的对象。当一个整数被赋给另一个整数时,两者指的是同一个对象。一旦我们修改了任何整数变量,就会创建一个新的 python 对象,而原始的 python 对象不受影响。您可以在下面的示例中观察到这一点。
num1 = 10
print("The id of first number is:", id(num1))
num2 = num1
print("The id of copied number is:", id(num2))
num1 = 15
print("The id of first number after modification:", id(num1))
print("The id of copied number after modification is:", id(num2))
输出:
The id of first number is: 9789248
The id of copied number is: 9789248
The id of first number after modification: 9789408
The id of copied number after modification is: 9789248
在这里,您可以看到在使用赋值操作符将num1复制到num2之后,num1和num2的 id 是相同的。然而,当我们修改num1时,num1的 id 会发生变化。
列表是可变的对象。当我们修改一个列表时,原始的列表对象也被修改。因此,在修改列表变量的过程中不会创建 python 对象,这种变化会反映在复制的和原始的列表变量中。您可以在下面的示例中观察到这一点。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The id of original list is:", id(list1))
list2 = list1
print("The id of copied list is:", id(list2))
list1.append(23)
print("The id of original list after modification is:", id(list1))
print("The id of copied list after modification is:", id(list2))
输出:
The id of original list is: 139879630222784
The id of copied list is: 139879630222784
The id of original list after modification is: 139879630222784
The id of copied list after modification is: 139879630222784
在这里,您可以看到,即使在list1中修改后,两个列表的 id 仍然相同。因此,即使在修改之后,也可以确认原始列表和复制列表引用相同的对象。
由于赋值操作不适用于在 python 中复制列表,我们将讨论在 python 中复制列表的不同方法。在此之前,我们先来讨论一下 python 中的id() 函数。
Python 中的 id()函数
每个 python 对象都有一个唯一的标识符。我们可以使用id()函数来获取与任何 python 对象相关联的标识符,如上面的例子所示。
如果两个变量作为输入传递给id()函数,给出相同的输出,那么这两个变量指的是同一个对象。
如果id()函数的输出对于不同的变量是不同的,那么它们指的是不同的对象。
在接下来的部分中,我们将使用id()函数来检查一个列表是否被复制。如果列表复制成功,两个列表的标识符将会不同。在这种情况下,当我们修改一个列表时,它不会影响另一个列表。
如果引用列表的两个变量的标识符相同,则这两个变量引用同一个列表。在这种情况下,在与变量关联的列表中所做的任何更改都将反映在与另一个变量关联的列表中。
有了这个背景,现在让我们来讨论在 python 中复制列表的不同方法。
使用 Python 中的 List()构造函数复制列表
list()构造函数用于从任何可迭代对象创建一个新的列表,比如列表、元组或集合。它将一个 iterable 对象作为其输入参数,并返回一个包含输入 iterable 对象元素的新列表。
为了使用 python 中的list()构造函数复制一个列表,我们将把原始列表作为输入参数传递给 list()构造函数。
执行后, list()构造函数将返回一个新的列表,其中包含原始列表中的元素。新列表和原始列表将具有不同的标识符,这些标识符可以使用id()方法获得。因此,对其中一个列表的任何更改都不会影响另一个列表。您可以在下面的示例中观察到这一点。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = list(list1)
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1.append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The id of original list is: 140137673798976
The copied list is: [1, 2, 3, 4, 5, 6, 7]
The id of copied list is: 140137673851328
The original list after modification is: [1, 2, 3, 4, 5, 6, 7, 10]
The copied list after modification is: [1, 2, 3, 4, 5, 6, 7]
在上面的例子中,你可以看到原始列表和复制列表的 id 是不同的。因此,对原始列表进行更改不会影响复制的列表。
使用 Python 中的 append()方法复制列表
方法用于向列表中添加一个新元素。当在列表上调用时,它将一个元素作为其输入参数,并将其添加到列表的最后一个位置。
为了使用 python 中的 append() 方法复制一个列表,我们将首先创建一个名为list_copy的空列表。之后,我们将使用 for 循环遍历原始列表。在迭代过程中,我们将使用append()方法将原始列表的每个元素添加到list_copy中。
执行 for 循环后,我们将在list_copy变量中获得复制的列表。您可以在下面的示例中观察到这一点。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = []
for element in list1:
list_copy.append(element)
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1.append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The id of original list is: 140171559405056
The copied list is: [1, 2, 3, 4, 5, 6, 7]
The id of copied list is: 140171560708032
The original list after modification is: [1, 2, 3, 4, 5, 6, 7, 10]
The copied list after modification is: [1, 2, 3, 4, 5, 6, 7]
您可以观察到新列表和原始列表具有不同的标识符,这些标识符是我们使用id()方法获得的。因此,对其中一个列表的任何更改都不会影响到另一个列表。
使用 Python 中的 extend()方法复制列表
方法用来一次添加多个元素到一个列表中。当在列表上调用时, extend() 方法将 iterable 对象作为其输入参数。执行后,它将输入 iterable 对象的所有元素追加到列表中。
为了使用extend()方法复制一个列表,我们将首先创建一个名为list_copy的空列表。之后,我们将调用list_copy上的extend() 方法,将原始列表作为其输入参数。执行后,我们将在list_copy变量中得到复制的列表。
新列表和原始列表将具有不同的标识符,这些标识符可以使用id() 方法获得。因此,对其中一个列表的任何更改都不会影响另一个列表。您可以在下面的示例中观察到这一点。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = []
list_copy.extend(list1)
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1.append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The id of original list is: 139960369243648
The copied list is: [1, 2, 3, 4, 5, 6, 7]
The id of copied list is: 139960370546624
The original list after modification is: [1, 2, 3, 4, 5, 6, 7, 10]
The copied list after modification is: [1, 2, 3, 4, 5, 6, 7]
在 Python 中使用切片复制列表
python 中的切片用于创建列表一部分的副本。切片的一般语法如下。
new_list=original_list[start_index:end_index]
这里,
new_list是执行语句后创建的列表。original_list是给定的输入列表。start_index是必须包含在new_list中的最左边元素的索引。如果我们让start_index为空,默认值为 0,列表从第一个元素开始复制。end_index是必须包含在new_list中的最右边元素的索引。如果我们让end_index为空,默认值就是列表的长度。因此,列表被复制到最后一个元素。
您可以使用切片来复制列表,如下例所示。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = list1[:]
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1.append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The id of original list is: 139834922264064
The copied list is: [1, 2, 3, 4, 5, 6, 7]
The id of copied list is: 139834923567040
The original list after modification is: [1, 2, 3, 4, 5, 6, 7, 10]
The copied list after modification is: [1, 2, 3, 4, 5, 6, 7]
您可以观察到新列表和原始列表具有不同的标识符,这些标识符是我们使用id() 方法获得的。因此,对其中一个列表的任何更改都不会影响另一个列表。
使用 Python 中的列表理解复制列表
L ist comprehension 用于通过对元素施加一些条件,使用现有列表的元素来创建新列表。列表理解的一般语法如下。
new_list=[element for element in existing_list if condition]
这里,
new_list是执行语句后创建的列表。existing_list是输入列表。element代表现有列表的元素。这个变量用于迭代existing_list。condition是对元素施加的条件。
这里,我们需要使用列表理解来复制一个给定的列表。因此,我们将不使用任何条件。下面是使用 python 中的 list comprehension 在 python 中复制列表的代码。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = [element for element in list1]
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1.append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The id of original list is: 139720431945088
The copied list is: [1, 2, 3, 4, 5, 6, 7]
The id of copied list is: 139720433248128
您可以观察到新列表和原始列表具有不同的标识符,这些标识符是我们使用id() 方法获得的。因此,对其中一个列表所做的任何更改都不会影响另一个列表。
使用 Python 中的 Copy()方法复制列表
Python 还为我们提供了在 python 中复制列表的copy()方法。在列表上调用copy()方法时,会返回原始列表的副本。新列表和原始列表将具有不同的标识符,这些标识符可以使用id() 方法获得。因此,对其中一个列表的任何更改都不会影响另一个列表。您可以在下面的示例中观察到这一点。
list1 = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = list1.copy()
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1.append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The id of original list is: 140450078000576
The copied list is: [1, 2, 3, 4, 5, 6, 7]
The id of copied list is: 140450079303616
The original list after modification is: [1, 2, 3, 4, 5, 6, 7, 10]
The copied list after modification is: [1, 2, 3, 4, 5, 6, 7]
在 Python 中复制列表列表
在 python 中复制列表的列表与复制列表不同。例如,让我们使用copy()方法复制 python 中的列表列表。
list1 = [[1, 2, 3], [4, 5, 6,], [7,8,9]]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = list1.copy()
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
输出:
The original list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of original list is: 139772961010560
The copied list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of copied list is: 139772961063040
这里,您可以看到原始列表和复制列表的 id 是不同的。这意味着两个列表是不同的 python 对象。尽管如此,当我们对原始列表进行任何修改时,它都会反映在修改后的列表中。您可以在下面的示例中观察到这一点。
list1 = [[1, 2, 3], [4, 5, 6, ], [7, 8, 9]]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = list1.copy()
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1[2].append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of original list is: 139948423344896
The copied list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of copied list is: 139948423397504
The original list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
The copied list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
这种情况是没有根据的。这是由于内存中列表的存储模式造成的。列表列表包含对内部列表的引用。
当我们使用copy()方法复制一个列表列表时,列表列表以及内部列表的引用也被复制。因此,不会复制内部列表,只会复制对内部列表的引用。因此,当我们对原始列表中的任何内部列表进行更改时,它也会反映在复制的列表中。
为了避免这种情况,我们可以迭代地复制列表列表的元素。
使用 Python 中的 append()方法复制列表列表
要使用 python 中的append() 方法复制列表列表,我们将使用以下步骤。
- 首先,我们将创建一个名为
list_copy的空列表。 - 之后,我们将使用 for 循环遍历列表列表。对于列表列表中的每个内部列表,我们将执行以下任务。
- 首先,我们将创建一个名为
temp的空列表。之后,我们将使用另一个 for 循环迭代内部列表的元素。 - 迭代时,我们将使用
append()方法将当前内部列表的元素追加到temp中。当在temp上被调用时,append()方法将从内部列表中获取一个元素作为输入参数,并将它附加到temp。
- 首先,我们将创建一个名为
- 遍历完当前内部列表的每个元素后,我们将把
temp追加到list_copy。之后,我们将移动到下一个内部列表,并重复前面的步骤。
一旦我们遍历了输入列表的所有内部列表,我们将在copy_list变量中获得列表的复制列表。您可以在下面的示例中观察到这一点。
list1 = [[1, 2, 3], [4, 5, 6, ], [7, 8, 9]]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = []
for inner_list in list1:
temp = []
for element in inner_list:
temp.append(element)
list_copy.append(temp)
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1[2].append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of original list is: 139893771608960
The copied list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of copied list is: 139893771661952
The original list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
The copied list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
迭代复制列表元素后,您可以看到原始列表中的修改不会影响复制的列表。
使用 Python 中的 extend()方法复制列表列表
除了使用append()方法,我们还可以使用extend()方法来复制 python 中的列表列表。为此,我们将使用以下步骤。
- 首先,我们将创建一个名为
list_copy的空列表。 - 之后,我们将使用 for 循环遍历列表列表。对于列表列表中的每个内部列表,我们将执行以下任务。
- 首先,我们将创建一个名为
temp的空列表。之后,我们将调用temp上的extend()方法,并将内部列表作为其输入参数。 - 然后,我们将把 temp 追加到
list_copy中。之后,我们将进入下一个内部列表。
一旦我们遍历了输入列表的所有内部列表,我们将在copy_list变量中获得列表的复制列表。您可以在下面的示例中观察到这一点。
list1 = [[1, 2, 3], [4, 5, 6, ], [7, 8, 9]]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = []
for inner_list in list1:
temp = []
temp.extend(inner_list)
list_copy.append(temp)
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1[2].append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of original list is: 140175921128448
The copied list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of copied list is: 140175921181312
The original list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
The copied list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
使用 Python 中的 Copy()方法复制列表列表
我们还可以使用copy()方法在 python 中复制一个列表列表。为此,我们将使用以下步骤。
- 首先,我们将创建一个名为
list_copy的空列表。 - 之后,我们将使用 for 循环遍历列表列表。对于列表列表中的每个内部列表,我们将执行以下任务。
- 我们将调用内部列表上的
copy()方法。我们将把copy()方法的输出分配给一个变量temp。 - 然后,我们将把 temp 追加到
list_copy中。之后,我们将进入下一个内部列表。
一旦我们遍历了输入列表的所有内部列表,我们将在copy_list变量中获得列表的复制列表。您可以在下面的示例中观察到这一点。
list1 = [[1, 2, 3], [4, 5, 6, ], [7, 8, 9]]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = []
for inner_list in list1:
temp = inner_list.copy()
list_copy.append(temp)
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1[2].append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of original list is: 140468123341760
The copied list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of copied list is: 140468123394560
The original list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
The copied list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
使用 Python 中的复制模块复制列表列表
copy模块为我们提供了deepcopy()方法,通过它我们可以复制嵌套的对象。deepcopy()方法将 python 对象作为输入参数,递归地复制输入对象的所有元素。
我们可以使用下面的例子所示的deepcopy()方法在 python 中复制一个列表列表。
import copy
list1 = [[1, 2, 3], [4, 5, 6, ], [7, 8, 9]]
print("The original list is:", list1)
print("The id of original list is:", id(list1))
list_copy = copy.deepcopy(list1)
print("The copied list is:", list_copy)
print("The id of copied list is:", id(list_copy))
list1[2].append(10)
print("The original list after modification is:", list1)
print("The copied list after modification is:", list_copy)
输出:
The original list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of original list is: 139677987171264
The copied list is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The id of copied list is: 139677987171776
The original list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
The copied list after modification is: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
您可以观察到新列表和原始列表具有不同的标识符,这些标识符是我们使用 id()方法获得的。因此,对一个列表的任何更改都不会影响另一个列表。
结论
在本文中,我们讨论了用 python 复制列表的不同方法。我们还研究了用 python 复制列表列表的不同方法。
要了解更多关于 python 编程的知识,你可以阅读这篇关于如何在 python 中检查排序列表的文章。您可能也会喜欢这篇关于如何用 python 将字典保存到文件中的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
用 Python 复制字典
原文:https://www.pythonforbeginners.com/dictionary/copy-dictionary-in-python
在编程时,可能会有我们需要精确复制字典的情况。在本文中,我们将研究用 python 复制字典的不同方法,并将实现这些方法。
使用 for 循环复制字典
我们可以通过遍历字典并将当前字典的条目添加到新字典中来创建一个 python 字典的副本。对于这个任务,我们可以使用 keys()方法首先获得字典中的键列表,然后我们可以将键和值对插入到另一个字典中。这可以如下进行。
myDict={1:1,2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict={}
keyList=myDict.keys()
for key in keyList:
newDict[key]=myDict[key]
print("Copied Dictionary is:")
print(newDict)
输出:
Original Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
当使用上述方法复制字典时,对字典中对象的引用被复制。因此,如果字典中有可变对象,并且我们对复制的字典进行了任何更改,那么这种更改将反映在原始字典中。如果我们有一个嵌套的字典,当我们在任何内部字典中进行更改时,该更改将会反映在复制的和原始的字典中。这可以从下面的例子中看出。
myDict={1:{1:1},2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict={}
keyList=myDict.keys()
for key in keyList:
newDict[key]=myDict[key]
print("Copied Dictionary is:")
print(newDict)
newDict[1][1]=4
print("Copied Dictionary after change:")
print(newDict)
print("Original Dictionary after change:")
print(myDict)
输出:
Original Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
Original Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
使用字典理解复制字典
当我们使用 list comprehension 来复制列表时,以类似的方式,我们可以使用字典理解来复制 python 中的字典,如下所示。
myDict={1:1,2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict={key:value for (key,value) in myDict.items()}
print("Copied Dictionary is:")
print(newDict)
输出:
Original Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
同样,复制的字典引用原始字典中的对象,当我们有一个嵌套字典并且我们对内部字典进行任何更改时,这些更改将在原始和复制的字典中反映出来。这可以从下面的例子中看出。
myDict={1:{1:1},2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict={key:value for (key,value) in myDict.items()}
print("Copied Dictionary is:")
print(newDict)
newDict[1][1]=4
print("Copied Dictionary after change:")
print(newDict)
print("Original Dictionary after change:")
print(myDict)
输出:
Original Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
Original Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
使用 dict.copy()方法
我们可以使用 dict.copy()方法来复制字典。在字典上调用 dict.copy()方法时,会返回原始字典的浅层副本。我们可以使用 dict.copy()复制字典,如下所示。
myDict={1:1,2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict=myDict.copy()
print("Copied Dictionary is:")
print(newDict)
输出:
Original Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
由于所创建的字典副本是浅层副本,所以新字典具有对原始字典的对象的引用。当我们在任一字典中对任何具有原始数据类型的键值对进行更改时,该更改不会显示在另一个字典中,但是当字典的值中包含可变对象时,在原始和复制的字典中都可以看到更改。例如,如果我们使用 dict.copy()方法复制了一个嵌套字典,并对复制的字典中的嵌套字典进行了更改,这些更改将在原始字典中可见。同样,当我们对原始字典进行更改时,它会反映在复制的字典中。这可以从下面的例子中看出。
myDict={1:{1:1},2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict=myDict.copy()
print("Copied Dictionary is:")
print(newDict)
newDict[1][1]=4
print("Copied Dictionary after change:")
print(newDict)
print("Original Dictionary after change:")
print(myDict)
输出:
Original Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
Original Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
使用 copy.copy()方法
创建字典浅层副本的另一种方法是使用 copy 模块中的 copy()方法。我们将要复制的字典作为参数传递给 copy.copy()方法,它创建作为参数传递的字典的浅层副本,并返回对它的引用。这可以如下进行。
import copy
myDict={1:1,2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict=copy.copy(myDict)
print("Copied Dictionary is:")
print(newDict)
输出:
Original Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
使用 copy.copy()方法创建的字典与使用 dict.copy()方法创建的字典工作方式相似。因此,如果存在嵌套字典,并且我们对任何内部字典进行了更改,则更改将会反映在复制的和原始的字典中。这可以从下面的例子中看出。
import copy
myDict={1:{1:1},2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict=copy.copy(myDict)
print("Copied Dictionary is:")
print(newDict)
newDict[1][1]=4
print("Copied Dictionary after change:")
print(newDict)
print("Original Dictionary after change:")
print(myDict)
输出:
Original Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
Original Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
使用 copy.deepcopy()方法
要创建一个不引用原始字典中对象的字典副本,我们可以使用复制模块中的 deepcopy()方法,如下所示。
import copy
myDict={1:1,2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict=copy.deepcopy(myDict)
print("Copied Dictionary is:")
print(newDict)
输出:
Original Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
deepcopy()方法递归地访问字典中的所有对象,并为每个元素创建一个新对象。当我们使用 copy.deepcopy()方法复制字典时,没有引用被复制。当我们对复制的字典中的对象进行任何更改时,即使它是一个嵌套字典,也不会对原始字典进行任何更改。类似地,当我们对原始字典进行更改时,这些更改不会反映在复制的字典中。这可以从下面的例子中看出。
import copy
myDict={1:{1:1},2:4,3:9,4:16}
print("Original Dictionary is:")
print(myDict)
newDict=copy.deepcopy(myDict)
print("Copied Dictionary is:")
print(newDict)
newDict[1][1]=4
print("Copied Dictionary after change:")
print(newDict)
print("Original Dictionary after change:")
print(myDict)
输出:
Original Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary is:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
Copied Dictionary after change:
{1: {1: 4}, 2: 4, 3: 9, 4: 16}
Original Dictionary after change:
{1: {1: 1}, 2: 4, 3: 9, 4: 16}
结论
在本文中,我们看到了用 python 复制字典的不同方法。我们还看到,dict.copy()和 copy.copy()方法创建一个复制的字典,它引用原始字典的对象,而我们可以使用 copy.deepcopy()方法创建一个复制的字典,它不引用原始字典中的元素。请继续关注更多内容丰富的文章。
用 Python 复制
原文:https://www.pythonforbeginners.com/data-types/copy-in-python
在 python 程序中,很多时候我们需要现有数据的相同副本。对于像 int、float、boolean 值或 string 这样的简单数据类型,赋值操作为我们完成了任务,因为它们是不可变的数据类型。复制之后,当我们对任何具有不可变数据类型的变量进行任何更改时,会创建一个新的数据实例,并且它们不会影响原始数据。在可变数据类型的情况下,如 list 或 dictionary,如果我们使用赋值操作符将数据复制到另一个变量,两个变量都引用同一个数据对象,如果我们对任何一个变量进行更改,对象也会发生变化,反映出对两个变量的影响。在本文中,我们将通过例子来理解 python 中复制的概念。
python 中如何获取对象的对象 ID?
为了说明 python 中复制的概念,我们需要知道对象的对象 ID。对于这个任务,我们将使用id()函数。该函数将变量名作为输入,并返回对象的唯一 id。从下面的例子可以看出这一点。
var1=1
print("ID of object at which var1 refers:",end=" ")
print(id(var1))
输出:
ID of object at which var1 refers: 9784896
在 python 中使用=运算符复制对象
当我们试图通过使用=操作符将一个变量赋给另一个变量来复制一个对象时,它不会创建一个新的对象,但是两个变量都被赋给了同一个对象。
例如,如果我们有一个名为 var1 的变量引用一个对象,我们通过语句var2=var1将 var1 赋给 var2,这两个变量指向同一个对象,因此将具有相同的 ID。这可以看如下。
var1=11
var2=var1
print("ID of object at which var1 refers:",end=" ")
print(id(var1))
print("ID of object at which var2 refers:", end=" ")
print(id(var2))
输出:
ID of object at which var1 refers: 9785216
ID of object at which var2 refers: 9785216
对于不可变对象,当我们改变赋给 var1 或 var2 中任何一个的值时,就会为新赋给该变量的值创建一个新对象。因此,如果我们更改分配给 var2 的值,将创建一个新对象,在重新分配后,var1 和 var2 将引用具有不同对象 ID 的对象。这可以这样理解。
var1=11
var2=var1
print("ID of object at which var1 refers:",end=" ")
print(id(var1))
print("ID of object at which var2 refers:", end=" ")
print(id(var2))
print("After Assigning value to var2")
var2=10
print("ID of object at which var1 refers:",end=" ")
print(id(var1))
print("ID of object at which var2 refers:", end=" ")
print(id(var2))
输出:
ID of object at which var1 refers: 9785216
ID of object at which var2 refers: 9785216
After Assigning value to var2
ID of object at which var1 refers: 9785216
ID of object at which var2 refers: 9785184
与上面不同的是,如果我们复制像列表这样的可变对象,在使用任何变量重新分配和修改导致同一个对象发生变化之后,它们指向同一个对象。这可以看如下。
list1=[1,2,3]
list2=list1
print("ID of object at which list1 refers:",end=" ")
print(id(list1))
print("ID of object at which list2 refers:", end=" ")
print(id(list2))
print("After appending another value to list2")
list2.append(4)
print("ID of object at which var1 refers:",end=" ")
print(id(list1))
print("ID of object at which var2 refers:", end=" ")
print(id(list2))
输出:
ID of object at which list1 refers: 140076637998720
ID of object at which list2 refers: 140076637998720
After appending another value to list2
ID of object at which var1 refers: 140076637998720
ID of object at which var2 refers: 140076637998720
在上面的输出中,我们可以看到,当我们使用赋值操作符复制 list 时,变量 list1 和 list2 引用同一个对象并具有相同的 ID。当我们对任何列表进行更改时,这不会改变。
如何在 Python 中复制可变对象?
对于复制像列表或字典这样的可变对象,我们使用copy()方法。
当在任何对象上调用时,copy()方法创建一个新的对象,其数据与原始对象相同,并返回对它的引用。这意味着当我们使用copy()方法而不是=操作符复制对象时,原始对象和复制对象的地址是不同的。
例如,如果我们使用copy()方法将 list1 复制到 list2,那么 list1 和 list2 将引用不同的对象。这可以看如下。
list1=[1,2,3]
list2=list1.copy()
print("ID of object at which list1 refers:",end=" ")
print(id(list1))
print("ID of object at which list2 refers:", end=" ")
print(id(list2))
print("After appending another value to list2")
list2.append(4)
print("ID of object at which var1 refers:",end=" ")
print(id(list1))
print("ID of object at which var2 refers:", end=" ")
print(id(list2))
输出:
ID of object at which list1 refers: 140076492253376
ID of object at which list2 refers: 140076483798272
After appending another value to list2
ID of object at which var1 refers: 140076492253376
ID of object at which var2 refers: 140076483798272
在输出中,可以看到 list2 与 list1 具有不同的对象 ID。如果我们修改 list1 中的任何值,都不会导致 list2 发生任何变化,而当我们使用= operator 将一个对象复制到另一个对象时,情况就不同了。
结论
在本文中,我们研究了如何在 python 中复制可变和不可变对象。对于不可变对象,我们可以使用= operator,因为在每次重新分配时,都会为不可变对象创建一个新对象。在像 python dictionary 这样的可变对象的情况下,我们应该使用copy()方法来复制像列表或字典这样的对象,以避免程序中不必要的错误。我们还可以使用 python try except 编写本文中使用的程序,以使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
在 Python 中计算整数的位数
原文:https://www.pythonforbeginners.com/basics/count-digits-of-an-integer-in-python
在 python 中,整数数据类型用于表示正整数和负整数。在本文中,我们将讨论一个用 python 计算整数位数的程序。
Python 中如何计算一个整数的位数?
为了计算一个数字的位数,我们将使用一种将数字除以 10 的方法。当我们将一个整数除以 10 时,得到的数减少了一位。
例如,如果我们将 1234 除以 10,结果将是 123。这里,1234 有 4 个数字,而 123 只有 3 个数字。类似地,当我们将 123 除以 10 时,它将被缩减为只有两位数的数,以此类推。最后,该数字将变为 0。
你可以观察到,在 1234 变成 0 之前,我们只能用 10 除它 4 次。换句话说,如果一个整数有 n 位,我们只能将这个整数除以 10n 次,直到它变成 0。
Python 中计算整数位数的程序
如上所述,我们将使用以下方法在 python 中计算数字的位数。
- 首先,我们将声明一个值计数,并将其初始化为 0。
- 然后,我们将使用 while 循环将给定的数反复除以 10。
- 在 while 循环中,每当我们将数字除以 10 时,count 就会增加 1。
- 一旦数字变为 0,我们将退出 while 循环。
- 在执行 while 循环之后,我们将获得 count 变量中整数的位数。
我们可以用 python 实现上述方法来计算数字的位数,如下所示。
number = 12345
print("The given number is:", number)
count = 0
while number > 0:
number = number // 10
count = count + 1
print("The number of digits is:", count)
输出:
The given number is: 12345
The number of digits is: 5
结论
在本文中,我们讨论了一种在 python 中计算整数位数的方法。想了解更多 python 中的数字,可以阅读这篇关于 python 中的十进制数字的文章。你可能也会喜欢这篇关于 python 中的复数的文章。
在 Python 中计算字符串中每个字符的出现次数
原文:https://www.pythonforbeginners.com/basics/count-occurrences-of-each-character-in-string-python
字符串操作是文本数据分析的关键组成部分之一。在分析文本数据时,我们可能需要计算文本中字符的出现频率。在本文中,我们将讨论 Python 中计算字符串中每个字符出现次数的不同方法。
使用 For 循环和 set()函数计算字符串中每个字符的出现次数
在 Python 中,我们可以使用 for 循环和 set() 函数来计算字符串中每个字符的出现次数。为此,我们将使用以下步骤。
- 首先,我们将创建一个包含输入字符串中所有字符的集合。为此,我们将使用
set()函数。set()函数将 iterable 对象作为其输入参数,并返回 iterable 对象的所有元素的集合。 - 创建字符集后,我们将使用嵌套的 for 循环来计算字符串中每个字符的出现次数。
- 在外部 for 循环中,我们将遍历集合中的元素。在 for 循环中,我们将定义一个变量
countOfChar,并将其初始化为 0。 - 然后,我们将使用另一个 for 循环迭代输入字符串。
- 在内部 for 循环中,如果我们在字符串中找到集合的当前字符,我们将把
countOfChar加 1。否则,我们将移动到字符串中的下一个字符。 - 在执行内部 for 循环后,我们将获得单个字符的计数。我们将使用 print 语句打印它。然后,我们将使用外部 for 循环移动到集合中的下一个字符。
执行 for 循环后,将打印字符串中每个字符出现的次数。您可以在下面的示例中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
for element in mySet:
countOfChar = 0
for character in input_string:
if character == element:
countOfChar += 1
print("Count of character '{}' is {}".format(element, countOfChar))
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
Count of character 'o' is 5
Count of character 'a' is 3
Count of character 'c' is 1
Count of character 'e' is 6
Count of character 'd' is 1
Count of character 't' is 8
Count of character 'r' is 5
Count of character 'y' is 2
Count of character 'n' is 4
Count of character 'u' is 1
Count of character 's' is 4
Count of character 'g' is 3
Count of character 'w' is 1
Count of character '.' is 1
Count of character 'h' is 3
Count of character ' ' is 9
Count of character 'P' is 2
Count of character 'b' is 1
Count of character 'i' is 3
Count of character 'f' is 1
如果你想存储字符的频率,你可以使用一个 python 字典。为了存储频率,我们将首先创建一个名为countOfChars的空字典。
计算完一个字符的计数后,我们将把这个字符作为键,把计数作为值添加到字典中。您可以在下面的代码中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
countOfChars = dict()
for element in mySet:
countOfChar = 0
for character in input_string:
if character == element:
countOfChar += 1
countOfChars[element] = countOfChar
print("Count of characters is:")
print(countOfChars)
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
Count of characters is:
{'s': 4, 'P': 2, 'b': 1, '.': 1, 'd': 1, 'c': 1, 'g': 3, 'r': 5, 'i': 3, 'o': 5, 'u': 1, 'a': 3, 'f': 1, 'e': 6, 'n': 4, 'y': 2, ' ': 9, 'w': 1, 't': 8, 'h': 3}
使用 Python 中的 Count()方法计算字符串中每个字符的出现次数
字符串中的count()方法用于统计字符串中某个字符出现的频率。当在字符串上调用时,count()方法将一个字符作为它的输入参数。执行后,它返回作为输入参数给出的字符的频率。
为了使用count()方法计算字符串中每个字符的出现次数,我们将使用以下步骤。
- 首先,我们将使用
set()函数在输入字符串中创建一组字符。 - 之后,我们将使用 for 循环遍历集合中的元素。
- 在 for 循环中,我们将调用输入字符串上的
count()方法,将集合中的当前元素作为其输入参数。执行后,count()方法将返回集合中当前元素的出现次数。我们将使用 print 语句打印该值。
在执行 for 循环后,将打印所有字符的频率。您可以在下面的示例中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
countOfChars = dict()
for element in mySet:
countOfChar = input_string.count(element)
countOfChars[element] = countOfChar
print("Count of character '{}' is {}".format(element, countOfChar))
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
Count of character 'e' is 6
Count of character 'n' is 4
Count of character 'a' is 3
Count of character '.' is 1
Count of character 'h' is 3
Count of character 'r' is 5
Count of character 'f' is 1
Count of character 'y' is 2
Count of character 's' is 4
Count of character 't' is 8
Count of character 'w' is 1
Count of character 'i' is 3
Count of character 'd' is 1
Count of character 'g' is 3
Count of character 'u' is 1
Count of character 'c' is 1
Count of character 'o' is 5
Count of character 'P' is 2
Count of character 'b' is 1
Count of character ' ' is 9
您还可以将字符的频率存储在字典中,如下所示。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
countOfChars = dict()
for element in mySet:
countOfChar = input_string.count(element)
countOfChars[element] = countOfChar
print("Count of characters is:")
print(countOfChars)
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
Count of characters is:
{'t': 8, 'o': 5, 'P': 2, 'n': 4, 'f': 1, 'e': 6, 'g': 3, 'c': 1, '.': 1, 's': 4, 'w': 1, 'y': 2, ' ': 9, 'u': 1, 'i': 3, 'd': 1, 'a': 3, 'h': 3, 'r': 5, 'b': 1}
上述方法具有很高的时间复杂度。如果字符串中有 N 个不同的字符,并且字符串长度为 M,则执行的时间复杂度将为 M*N。因此,如果必须分析数千个字符的字符串,则不建议使用这些方法。为此,我们可以使用下面几节中讨论的其他方法。
使用 Python 字典来统计字符串中每个字符的出现次数
python 中的字典存储键值对。为了使用字典计算 Python 中字符串中每个字符的出现次数,我们将使用以下方法。
- 首先,我们将创建一个名为
countOfChars的空字典来存储字符及其频率。 - 现在,我们将使用 for 循环迭代输入字符串。
- 在迭代过程中,我们将使用成员操作符检查当前字符是否存在于字典中。
- 如果该字符出现在字典中,我们将把与该字符相关的值增加 1。否则,我们将把这个字符作为一个键添加到字典中,1 作为它的关联值。
在执行 for 循环之后,我们将获得countOfChars字典中每个字符的计数。您可以在下面的示例中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
countOfChars = dict()
for character in input_string:
if character in countOfChars:
countOfChars[character] += 1
else:
countOfChars[character] = 1
print("The count of characters in the string is:")
print(countOfChars)
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
{'P': 2, 'y': 2, 't': 8, 'h': 3, 'o': 5, 'n': 4, 'f': 1, 'r': 5, 'b': 1, 'e': 6, 'g': 3, 'i': 3, 's': 4, ' ': 9, 'a': 3, 'u': 1, 'c': 1, 'd': 1, 'w': 1, '.': 1}
不使用 if else 语句,可以使用 python try-except 块来计算字符串中字符的出现次数。
- 在 for 循环中,我们将在 try 块中将字典中与当前字符相关联的值增加 1。如果该字符在字典中不存在,程序将引发一个 KeyError 异常。
- 在 except 块中,我们将捕获 KeyError 异常。这里,我们将把字符作为一个键分配给字典,1 作为它的关联值。
在执行 for 循环之后,我们将获得countOfChars字典中每个字符的计数。您可以在下面的示例中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
countOfChars = dict()
for character in input_string:
try:
countOfChars[character] += 1
except KeyError:
countOfChars[character] = 1
print("The count of characters in the string is:")
print(countOfChars)
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
{'P': 2, 'y': 2, 't': 8, 'h': 3, 'o': 5, 'n': 4, 'f': 1, 'r': 5, 'b': 1, 'e': 6, 'g': 3, 'i': 3, 's': 4, ' ': 9, 'a': 3, 'u': 1, 'c': 1, 'd': 1, 'w': 1, '.': 1}
如果我们有一个很大的输入字符串,与字符串的长度相比,只有很少的不同字符,那么使用 try-except 块的方法效果最好。如果输入字符串很小,并且输入字符串的长度不是非常大于不同字符的总数,那么这种方法会比较慢。这是因为处理异常是一项开销很大的操作。
如果程序非常频繁地引发 KeyError 异常,将会降低程序的性能。因此,您应该根据输入字符串长度和字符串中不同字符的数量,选择使用 if-else 语句还是 try-except 块。
还可以避免同时使用 if else 语句和 try-except 块。为此,我们需要使用以下方法。
- 首先,我们将使用
set()函数在原始字符串中创建一组字符。 - 然后,我们将使用集合的元素作为键,使用 0 作为关联值来初始化字典
countOfChars。 - 现在,我们将使用 for 循环遍历输入字符串的字符。在迭代过程中,我们将把与当前字符相关的值加 1。
在执行 for 循环后,我们将获得字符串中每个字符的出现次数。您可以在下面的示例中观察到这一点。
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
mySet = set(input_string)
countOfChars = dict()
for element in mySet:
countOfChars[element] = 0
for character in input_string:
countOfChars[character] += 1
print("The count of characters in the string is:")
print(countOfChars)
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
{'d': 1, 'r': 5, 'y': 2, 'a': 3, 'P': 2, 'i': 3, 's': 4, ' ': 9, 'f': 1, '.': 1, 'h': 3, 't': 8, 'g': 3, 'c': 1, 'u': 1, 'e': 6, 'n': 4, 'w': 1, 'o': 5, 'b': 1}
使用集合计算字符串中每个字符的出现次数。Counter()函数
集合模块为我们提供了各种函数来处理集合对象,如列表、字符串、集合等。Counter()函数就是其中之一。它用于计算集合对象中元素的出现频率。
Counter()函数接受一个集合对象作为它的输入参数。执行后,它返回一个集合计数器对象。计数器对象以字典的形式包含所有字符及其频率。
要计算 Python 中一个字符串中每个字符的出现次数,只需将它传递给Counter()函数并打印输出,如下例所示。
from collections import Counter
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
countOfChars = Counter(input_string)
print("The count of characters in the string is:")
print(countOfChars)
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
Counter({' ': 9, 't': 8, 'e': 6, 'o': 5, 'r': 5, 'n': 4, 's': 4, 'h': 3, 'g': 3, 'i': 3, 'a': 3, 'P': 2, 'y': 2, 'f': 1, 'b': 1, 'u': 1, 'c': 1, 'd': 1, 'w': 1, '.': 1})
使用 Collections.defaultdict()
集合模块为我们提供了一个具有增强特性的字典对象。这叫defaultdict。如果您试图修改与字典中不存在的键相关联的值,defaultdict对象不会引发 KeyError 异常。相反,它自己创建一个密钥,然后继续执行语句。
例如,如果在一个简单的字典中没有名为 “Aditya”的键,而我们执行了操作myDict[“Aditya”]+=1,程序将会遇到一个 KeyError 异常。另一方面,defaultdict对象将首先在字典中创建键“Aditya”,并将成功执行上述语句。但是,我们需要帮助 defaultdict 对象创建键的默认值。
defaultdict()函数接受另一个函数,比如说fun1作为它的输入参数。每当 defaultdict 对象需要创建一个带有默认值的新键时,它就会执行fun1,并使用fun1返回的值作为新键的关联值。在我们的例子中,我们需要一个字符计数的默认值 0,我们将把int()函数作为输入参数传递给defaultdict()函数。
为了使用 Python 中的 defaultdict 对象计算字符串中每个字符的出现次数,我们将使用以下步骤。
- 首先,我们将使用
collections.defaultdict()函数创建一个 defaultdict 对象。这里,我们将把int()函数作为输入参数传递给defaultdict()函数。 - 然后,我们将使用 for 循环遍历输入字符串的字符。
- 在迭代过程中,我们将不断增加与 defaultdict 对象中每个字符相关的值。
在执行 for 循环后,我们将获得 defaultdict 对象中每个字符的计数。您可以在下面的示例中观察到这一点。
from collections import defaultdict
input_string = "Pythonforbeginners is a great source to get started with Python."
print("The input string is:", input_string)
countOfChars = defaultdict(int)
for character in input_string:
countOfChars[character] += 1
print("The count of characters in the string is:")
print(countOfChars)
输出:
The input string is: Pythonforbeginners is a great source to get started with Python.
The count of characters in the string is:
defaultdict(<class 'int'>, {'P': 2, 'y': 2, 't': 8, 'h': 3, 'o': 5, 'n': 4, 'f': 1, 'r': 5, 'b': 1, 'e': 6, 'g': 3, 'i': 3, 's': 4, ' ': 9, 'a': 3, 'u': 1, 'c': 1, 'd': 1, 'w': 1, '.': 1})
结论
在本文中,我们讨论了 python 中计算字符串中每个字符出现次数的不同方法。在所有这些方法中,我建议您使用使用集合模块的方法,因为这些是最有效的方法。
我希望你喜欢阅读这篇文章。想了解更多关于 python 编程的知识,可以阅读这篇关于 Python 中字典理解的文章。你可能也会喜欢这篇关于机器学习中回归的文章。你也可以看看这篇关于数据分析师 vs 数据科学家的文章。
请继续关注更多内容丰富的文章。快乐学习!
计算列表中元素的出现频率
原文:https://www.pythonforbeginners.com/lists/count-the-frequency-of-elements-in-a-list
很多时候,我们需要在 python 中对数据进行定量分析。在本文中,我们将研究一些统计列表中元素出现频率的方法。列表中元素的频率被定义为它在列表中出现的次数。
使用 for 循环计算列表中元素的频率
我们可以使用 python 字典来计算列表中元素的频率。为了执行这个操作,我们将创建一个字典,其中包含来自输入列表的惟一元素作为键,它们的计数作为值。
为了统计列表中元素的频率,首先,我们将创建一个空字典。之后,对于每一个新元素,我们会统计该元素在列表中的出现频率。在获得元素的频率后,我们将把元素及其频率作为键-值对添加到字典中。
我们还将维护一个已访问元素的列表,以过滤掉已经访问过的元素。这可以如下进行。
myList = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
frequencyDict = dict()
visited = set()
listLength = len(myList)
for i in range(listLength):
if myList[i] in visited:
continue
else:
count = 0
element = myList[i]
visited.add(myList[i])
for j in range(listLength - i):
if myList[j+i] == element:
count += 1
frequencyDict[element] = count
print("Input list is:", myList)
print("Frequency of elements is:")
print(frequencyDict)
输出:
Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
Frequency of elements is:
{1: 2, 2: 2, 3: 3, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1}
在上面的例子中,我们为每个唯一的元素迭代整个列表。这使得算法效率低下。在最坏的情况下,当列表包含所有唯一元素时,我们将不得不处理所有元素至少 n*(n+1)/2 次,其中 n 是列表的长度。
为了克服这个缺点,我们将修改上面的算法。作为一个改进,我们将只遍历列表一次。为了统计元素的频率,我们将遍历列表,检查每个元素是否已经作为一个键出现在字典中。如果当前元素已经作为一个键出现在字典中,我们将把与该元素相关的计数加 1。如果当前元素还没有作为一个键出现在字典中,我们将添加一个新的条目到字典中,当前元素作为键,1 作为它的关联值。
我们可以如下实现这个算法。
myList = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
frequencyDict = dict()
visited = set()
for element in myList:
if element in visited:
frequencyDict[element] = frequencyDict[element] + 1
else:
frequencyDict[element] = 1
visited.add(element)
print("Input list is:", myList)
print("Frequency of elements is:")
print(frequencyDict)
输出:
Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
Frequency of elements is:
{1: 2, 2: 2, 3: 3, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1}
在 except 块中,我们将捕获KeyError并将一个新的键-值对添加到字典中,将当前元素作为键,将 1 作为其关联值。这将按如下方式进行。
myList = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
frequencyDict = dict()
for element in myList:
try:
frequencyDict[element] = frequencyDict[element] + 1
except KeyError:
frequencyDict[element] = 1
print("Input list is:", myList)
print("Frequency of elements is:")
print(frequencyDict)
输出:
Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
Frequency of elements is:
{1: 2, 2: 2, 3: 3, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1}
在上述两种算法中,使用 for 循环实现的解决方案对于每种类型的输入列表都具有几乎相同的效率。然而,对于只有少数元素在列表中重复多次的输入列表,使用异常处理的解决方案会执行得更快。
使用 counter()方法计算频率
我们可以使用集合模块中的 counter()方法来计算列表中元素的出现频率。counter()方法接受一个 iterable 对象作为输入参数。它返回一个计数器对象,该对象以键值对的形式存储所有元素的频率。我们可以使用 counter()方法来计算列表中元素的频率,如下所示。
import collections
myList = [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
frequencyDict = collections.Counter(myList)
print("Input list is:", myList)
print("Frequency of elements is:")
print(frequencyDict)
输出:
Input list is: [1, 2, 3, 4, 1, 3, 46, 7, 2, 3, 5, 6, 10]
Frequency of elements is:
Counter({3: 3, 1: 2, 2: 2, 4: 1, 46: 1, 7: 1, 5: 1, 6: 1, 10: 1})
结论
在本文中,我们讨论了计算列表中元素出现频率的不同方法。要阅读更多关于列表的内容,请阅读这篇关于 python 中的列表理解的文章。请继续关注更多内容丰富的文章。
用 Python 从字符串创建字典
原文:https://www.pythonforbeginners.com/basics/create-a-dictionary-from-a-string-in-python
字符串和字典是 Python 中最常用的两种数据结构。在 Python 中,我们使用字符串进行文本分析。另一方面,字典用于存储键值对。在本文中,我们将讨论如何用 Python 从字符串创建字典。
使用 for 循环从字符串创建字典
为了用 Python 从一个字符串创建一个字典,我们可以使用一个 python for 循环。在这种方法中,我们将创建一个字典,其中包含原始字符串中所有字符的计数。为了从给定的字符串创建字典,我们将使用以下步骤。
- 首先,我们将使用
dict()函数创建一个空的 python 字典。 - 接下来,我们将使用 for 循环遍历字符串中的字符。
- 在迭代时,我们将首先检查该字符是否已经存在于字典中。如果是,我们将增加与字典中的字符相关的值。否则,我们将把这个字符作为一个键,1 作为关联值赋给字典。
在执行 for 循环之后,我们将得到字典,其中包含作为键的字符串的字符和作为值的它们的频率。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=dict()
for character in myStr:
if character in myDict:
myDict[character]+=1
else:
myDict[character]=1
print("The dictionary created from characters of the string is:")
print(myDict)
输出:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
{'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, ' ': 2, 'F': 1, 'r': 2, 'B': 1, 'e': 2, 'g': 1, 'i': 1, 's': 1}
使用计数器方法从字符串中查找字典
为了从 python 中的字符串创建字典,我们还可以使用集合模块中定义的Counter()方法。Counter()方法将一个字符串作为输入参数,并返回一个计数器对象。计数器对象包含作为键的字符串的所有字符,以及作为相关值的它们的频率。您可以在下面的示例中观察到这一点。
from collections import Counter
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=dict(Counter(myStr))
print("The dictionary created from characters of the string is:")
print(myDict)
输出:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
{'P': 1, 'y': 1, 't': 1, 'h': 1, 'o': 2, 'n': 3, ' ': 2, 'F': 1, 'r': 2, 'B': 1, 'e': 2, 'g': 1, 'i': 1, 's': 1}
使用 Dict.fromkeys()方法从字符串中查找字典
我们还可以使用fromkeys()方法从 python 中的一个字符串创建一个字典。fromkeys() 方法将一个字符串作为第一个输入参数,将一个默认值作为第二个参数。执行后,它返回一个字典,其中包含作为键的字符串的所有字符,以及作为每个键的关联值的输入值。如果您想为字典的所有键提供一个默认的关联值,您可以使用fromkeys()方法从一个字符串创建一个字典,如下所示。
from collections import Counter
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=dict.fromkeys(myStr,0)
print("The dictionary created from characters of the string is:")
print(myDict)
输出:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
{'P': 0, 'y': 0, 't': 0, 'h': 0, 'o': 0, 'n': 0, ' ': 0, 'F': 0, 'r': 0, 'B': 0, 'e': 0, 'g': 0, 'i': 0, 's': 0}
如果不想向fromkeys()方法传递任何默认值,可以选择省略。在这种情况下,从字符串创建的字典的所有键都没有关联值。您可以在下面的示例中观察到这一点。
from collections import Counter
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=dict.fromkeys(myStr)
print("The dictionary created from characters of the string is:")
print(myDict)
输出:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
{'P': None, 'y': None, 't': None, 'h': None, 'o': None, 'n': None, ' ': None, 'F': None, 'r': None, 'B': None, 'e': None, 'g': None, 'i': None, 's': None}
使用 Ordereddict.fromkeys()方法
除了字典,您还可以从 Python 中的字符串获得有序字典。如果您想为字典的所有键提供一个默认的关联值,您可以使用fromkeys()方法从一个字符串创建一个有序字典。fromkeys()方法将一个字符串作为第一个输入参数,将一个默认值作为第二个参数。执行后,它返回一个有序字典,其中包含作为键的字符串的所有字符。您可以在下面的示例中观察到这一点。
from collections import OrderedDict
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=OrderedDict.fromkeys(myStr,0)
print("The dictionary created from characters of the string is:")
print(myDict)
输出:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
OrderedDict([('P', 0), ('y', 0), ('t', 0), ('h', 0), ('o', 0), ('n', 0), (' ', 0), ('F', 0), ('r', 0), ('B', 0), ('e', 0), ('g', 0), ('i', 0), ('s', 0)])
如果不想向 fromkeys()方法传递任何默认值,可以选择省略。在这种情况下,从字符串创建的有序字典的所有键都没有关联值。您可以在下面的示例中观察到这一点。
from collections import OrderedDict
myStr="Python For Beginners"
print("The input string is:",myStr)
myDict=OrderedDict.fromkeys(myStr)
print("The dictionary created from characters of the string is:")
print(myDict)
输出:
The input string is: Python For Beginners
The dictionary created from characters of the string is:
OrderedDict([('P', None), ('y', None), ('t', None), ('h', None), ('o', None), ('n', None), (' ', None), ('F', None), ('r', None), ('B', None), ('e', None), ('g', None), ('i', None), ('s', None)])
结论
在本文中,我们讨论了用 Python 从字符串创建字典的不同方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于字符串操作的文章。您可能也会喜欢这篇关于 python simplehttpserver 的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
使用 Python 中的类创建装饰者
原文:https://www.pythonforbeginners.com/basics/create-decorators-using-classes-in-python
您可能知道如何使用函数在 python 中创建装饰器。在本文中,我们将讨论使用 Python 中的类来创建 decorators 的方法。首先我们将讨论什么是可调用对象,然后我们将通过为它们定义类来实现使用这些可调用对象的装饰器。
什么是可调用对象?
python 中任何可以像函数和方法一样调用的对象都称为可调用对象。在 python 中,每个可调用对象在其类定义中都有 call()方法的实现。我们可以说,任何在类定义中有_ _ call _ __()方法的对象都称为可调用对象。
要调用一个对象,我们需要在对象的类定义中实现_ _ call _ __()方法。
例如,看看下面的源代码。
class Car:
def __init__(self):
self.brand = "Tesla"
self.speed = "100mph"
def __call__(self, *args, **kwargs):
print("Called me? I am coming at {} speed.".format(self.speed))
在这里,我们定义了一个名为 汽车 的类。除了它的构造函数定义,我们还在它的类定义中定义了 call ()方法。现在我们可以调用 Car 类的任何实例,下面将执行 call ()方法。
class Car:
def __init__(self):
self.brand = "Tesla"
self.speed = "100mph"
def __call__(self, *args, **kwargs):
print("Called me? I am coming at {} speed.".format(self.speed))
# create callable object
myCar = Car()
# call myCar
myCar()
输出:
Called me? I am coming at 100mph speed.
我们可以使用任何一个接受函数或可调用对象作为输入并返回可调用对象或函数的可调用对象来实现 python 装饰器。
如何使用类创建 decorators?
通过使用 call()方法定义可调用对象,我们可以使用类来创建 decorators,这一点我们将在本节中讨论。
首先,我们将定义一个函数 add (),它将两个数字作为输入,并打印它们的和。
def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
# execute
add(10, 20)
输出:
The sum of 10 and 20 is 30.
现在,我们必须以这样的方式定义一个装饰器,即 add ()函数还应该打印数字的乘积以及总和。为此,我们可以创建一个装饰类。
我们可以在一个类内部实现_ __ _ call _ _()方法来实现 decorators。
首先,我们将定义 decorator_class 的构造函数,它接受 add ()函数作为输入参数,并将其赋给一个类变量 func 。
然后我们将实现_ _ call _ __()方法。 call ()方法中的代码将计算输入数字的乘积并打印出来。之后,它将使用给定的输入数字调用输入函数 add()。最后,它将返回 add()函数返回的值。
class decorator_class:
def __init__(self, func):
self.func = func
def __call__(self, *args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
return self.func(args[0], args[1])
在 call ()方法中,我们实现了打印作为输入给出的数字的乘积,然后在调用 add ()函数后返回其输出的代码。()函数打印输入数字的和。我们已经定义了函数和装饰类,让我们看看如何使用它们。
通过将函数作为参数传递给类构造函数来创建装饰器
要创建装饰函数,我们可以将 add ()函数作为输入参数传递给装饰器类的构造函数。将 add ()函数赋给decorator _ class中的 func 变量。一旦decorator _ class的实例被调用,它将执行 call ()方法内的代码来打印输入数字的乘积。然后它调用后会返回函数 func 的输出。由于 加上 ()的功能已经赋值给 func ,它将打印出数字的总和。
*`class decorator_class:
def __init__(self, func):
self.func = func
def __call__(self, *args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
return self.func(args[0], args[1])
def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
# execute
decorator_object = decorator_class(add)
decorator_object(10, 20)`*
输出:
*`Product of 10 and 20 is 200
The sum of 10 and 20 is 30.`*
使用@符号创建装饰者
我们可以在定义()函数之前,用 @ 符号指定 decorator_class 名称,而不是将 add 函数传递给类构造函数。此后,每当调用 add ()函数时,它总是打印输入数字的乘积和总和。**
**`class decorator_class:
def __init__(self, func):
self.func = func
def __call__(self, *args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
return self.func(args[0], args[1])
@decorator_class
def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
# execute
add(10, 20)`**
输出:
**`Product of 10 and 20 is 200
The sum of 10 and 20 is 30.`**
这种方法有一个缺点,就是在用@ sign 定义修饰函数的时候,不能用 add ()函数仅仅把数字相加。它总是打印数字的乘积以及它们的总和。因此,如果您在任何其他地方以原始形式使用 add()函数,将会导致错误。
结论
在本文中,我们讨论了使用 python 中的类创建 Python 装饰器的方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
从 Python 中的列表创建生成器
原文:https://www.pythonforbeginners.com/basics/create-generator-from-a-list-in-python
Python 中的生成器是从容器对象中访问元素的非常有用的工具。在本文中,我们将讨论如何从一个列表中创建一个生成器,以及为什么我们需要这样做。这里我们将使用两种方法从列表中创建生成器。第一次使用生成器函数,第二次使用生成器理解。
使用生成器函数将列表转换为生成器
生成器函数是那些用产生语句而不是返回语句的函数。生成器函数有一个特点,一旦 yield 语句被执行,它们就暂停执行。为了恢复生成器函数的执行,我们只需要使用 next()函数,将生成器函数作为输入参数分配给生成器。
例如,假设我们想要一个给定列表的元素的平方。获得元素的平方的一种方式可以是使用列表理解或函数来创建具有现有列表的元素的平方的新列表,如下所示。
def square(input_list):
square_list = []
for i in input_list:
square_list.append(i ** 2)
return square_list
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
squares = square(myList)
print("Elements obtained from the square function are:")
for ele in squares:
print(ele)
输出:
The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements obtained from the square function are:
1
4
9
16
25
36
49
64
81
100
我们也可以创建一个生成器来代替一个新的列表,使用生成器函数来获得现有列表元素的平方。
为了使用 generator 函数从一个列表中创建一个生成器,我们将定义一个接受列表作为输入的生成器函数。在函数内部,我们将使用一个 for 循环,其中 yield 语句将用于给出现有列表元素的平方作为输出。我们可以如下执行此操作。
def square(input_list):
square_list = []
for element in input_list:
yield element ** 2
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
squares = square(myList)
print("Elements obtained from the square generator are:")
for ele in squares:
print(ele)
输出:
The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements obtained from the square generator are:
1
4
9
16
25
36
49
64
81
100
使用生成器理解将列表转换为生成器
我们可以使用 generator comprehension 从列表中创建一个生成器,而不是使用生成器函数。生成器理解的语法几乎与列表理解相同。
集合理解的语法是:生成器 = ( 表达式 for 元素initerableif条件 )
您可以使用 generator comprehension 从列表中创建一个生成器,如下所示。这里,我们使用了与上一节中给出的相同的实现示例。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("The given list is:", myList)
mygen = (element ** 2 for element in myList)
print("Elements obtained from the generator are:")
for ele in mygen:
print(ele)
输出:
The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Elements obtained from the generator are:
1
4
9
16
25
36
49
64
81
100
为什么要从列表中创建生成器?
生成器可以用来代替列表,原因有两个。让我们逐一了解他们两个。
- 当我们从一个现有的列表创建一个新的列表时,程序使用内存来存储现有列表的元素。另一方面,生成器使用最少量的内存,几乎与函数所需的内存相似。因此,如果我们只需要从新创建的列表中访问元素,使用生成器代替列表会更有效。
- 有了生成器,我们可以在不显式使用任何计数器的情况下随机访问列表的下一个元素。为此,我们可以使用 next()方法从生成器中提取下一个元素。
例如,考虑这样一种情况,我们有一个 100 个元素的列表。我们不断地要求用户输入一个数字,只要他们输入一个偶数,我们就打印列表的下一个元素。
这里,用户输入没有任何模式。因此,我们不能使用 for 循环来访问列表中的元素。相反,我们将使用一个生成器,通过 next()函数打印列表中的下一个元素,如下例所示。
myList = range(0, 101)
myGen = (element ** 2 for element in myList)
while True:
user_input = int(input("Input an even number to get an output, 0 to exit:"))
if user_input == 0:
print("Good Bye")
break
elif user_input % 2 == 0:
print("Very good. Here is an output for you.")
print(next(myGen))
else:
print("Input an even number.")
continue
输出:
Input an even number to get an output, 0 to exit:23
Input an even number.
Input an even number to get an output, 0 to exit:123
Input an even number.
Input an even number to get an output, 0 to exit:12
Very good. Here is an output for you.
0
Input an even number to get an output, 0 to exit:34
Very good. Here is an output for you.
1
Input an even number to get an output, 0 to exit:35
Input an even number.
Input an even number to get an output, 0 to exit:0
Good Bye
结论
在本文中,我们讨论了从列表创建生成器的两种方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
在熊猫系列中创建索引
原文:https://www.pythonforbeginners.com/basics/create-index-in-a-pandas-series
Pandas 系列对象用于存储数据,当我们需要使用它的位置和标签来访问它时。在本文中,我们将讨论在熊猫系列中创建索引的不同方法。
使用 Index 参数在熊猫系列中创建索引
当我们创建一个熊猫系列时,它有一个默认索引,从 0 开始到系列长度-1。例如,考虑下面的例子。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
series=pd.Series(letters)
print("The series is:")
print(series)
输出:
The series is:
0 a
1 b
2 c
3 ab
4 abc
5 abcd
6 bc
7 d
dtype: object
在上面的例子中,我们创建了一系列的 8 个元素。您可以观察到序列中元素的索引从 0 到 7 进行编号。这些是默认索引。
如果您想为序列分配一个自定义索引,您可以使用Series()构造函数中的index参数。Series()构造函数中的 index 参数获取一个元素数量与序列中的元素数量相等的列表,并为序列创建一个自定义索引,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters,index=numbers)
print("The series is:")
print(series)
输出:
The series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在上面的例子中,我们已经将 python 列表 [3,23,11,14,16,2,45,65]传递给 Series()构造函数的 index 参数。在执行了Series()构造函数之后,这个列表的元素被指定为序列中元素的索引。
使用 Index 属性在熊猫系列中创建索引
您也可以在创建系列后为系列创建新的索引。例如,如果您想将其他值指定为序列中的索引,您可以使用 series 对象的index属性。要创建一个新的定制索引,您可以为属性index分配一个值列表,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The series is:")
print(series)
输出:
The series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在本例中,我们在创建系列后,将列表[3, 23, 11, 14, 16, 2, 45, 65]分配给系列的index属性。因此,该列表的元素被指定为序列中元素的索引。
这里,传递给 index 属性的列表的长度必须等于序列中元素的数量。否则,程序会遇到值错误异常。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65,117]
series=pd.Series(letters)
series.index=numbers
print("The series is:")
print(series)
输出:
ValueError: Length mismatch: Expected axis has 8 elements, new values have 9 elements
在上面的例子中,您可以观察到列表"letters" 只有 8 个元素。因此,该系列仅包含 8 个元素。另一方面,列表"numbers" 具有 9 个元素。因此,当我们将"numbers" 列表赋给序列的索引属性时,程序会遇到 ValueError 异常。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇 MLFlow 教程,里面有代码示例。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
使用 set_axis()方法在熊猫系列中创建一个索引
我们可以使用set_axis() 方法在熊猫系列中创建一个索引,而不是使用index属性。
set_axis()方法
set_axis()方法具有以下语法。
Series.set_axis(labels, *, axis=0, inplace=_NoDefault.no_default, copy=_NoDefault.no_default)
这里,
labels参数接受一个包含索引值的类似列表的对象。您还可以将一个索引对象传递给labels参数。传递给 labels 参数的任何对象中的元素数量应该与调用set_axis()方法的序列中的元素数量相同。axis参数用于决定我们是否想要为行或列创建索引。因为一个系列只有一列,所以没有使用axis参数。- 创建新索引后,
set_axis()方法返回一个新的 Series 对象。如果要修改原来的系列对象,可以将inplace参数设置为 True。 copy参数用于决定是否复制底层数据,而不是修改原始序列。默认情况下,这是真的。
为了使用set_axis()方法创建一个索引,我们将在原始的 series 对象上调用这个方法。我们将把包含新索引值的列表作为输入参数传递给set_axis()方法。执行后,set_axis()方法将返回一个新的序列,该序列的索引已被修改。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series=series.set_axis(labels=numbers)
print("The series is:")
print(series)
输出:
The series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在这个例子中,我们首先创建了一个包含 8 个元素的序列。然后,我们使用set_index()方法为序列中的元素分配新的索引。您可以观察到set_index() 方法返回了一个新的序列。因此,原始系列不会被修改。若要通过分配新的索引而不是创建新的索引来修改原始序列,可以在序列中就地创建索引。
在熊猫系列中就地创建索引
要在 pandas 系列中就地创建索引,可以将新索引分配给 series 对象的index属性,如下例所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.index=numbers
print("The series is:")
print(series)
输出:
The series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
您也可以使用set_axis() 方法在序列中创建一个索引。为此,您可以将包含新索引值的列表传递给set_axis() 方法,并在调用原始 series 对象上的set_axis()方法时将inplace参数设置为 True。执行后,您将获得如下所示的修改后的 series 对象。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,11,14,16,2,45,65]
series=pd.Series(letters)
series.set_axis(labels=numbers,inplace=True)
print("The series is:")
print(series)
输出:
The series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在这个例子中,我们使用了set_index() 方法为序列中的元素分配新的索引。您可以观察到我们已经在set_index() 方法中将inplace参数设置为 True。因此,新的索引是在原始系列对象本身中分配的。
使用inplace参数时,您将得到一个表示"FutureWarning: Series.set_axis 'inplace' keyword is deprecated and will be removed in a future version. Use obj = obj.set_axis(..., copy=False) instead"的未来警告。这意味着inplace参数已经被弃用。因此,如果在熊猫的未来版本中使用相同的代码,程序可能会出错。为了避免这种情况,您可以使用copy参数。
默认情况下,copy参数设置为真。因此,set_axis()方法使用原始序列的副本并修改它。如果您想修改原始序列,您可以在set_axis()方法中将copy参数设置为 False。
结论
在本文中,我们讨论了用 Python 在 pandas 系列中创建索引的不同方法。要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
在 Python 中创建 Numpy 数组
原文:https://www.pythonforbeginners.com/basics/create-numpy-array-in-python
Numpy 数组在 python 中使用,特别是在数据分析、机器学习和数据科学中,用来操作数字数据。在本文中,我们将讨论使用示例和工作代码在 Python 中创建 numpy 数组的不同方法。
Python 中有各种创建 numpy 数组的函数。让我们逐一讨论。
Python 中 Numpy 数组的列表
我们可以使用numpy.array()函数从 python 列表中创建一个 numpy 数组。array()函数将一个列表作为其输入参数,并返回一个 numpy 数组。在这种情况下,数组元素的数据类型与列表中元素的数据类型相同。
myList=[1,2,3,4,5]
print("The list is:")
print(myList)
myArr = np.array(myList)
print("The array is:")
print(myArr)
print("The data type of array is:")
print(myArr.dtype)
输出:
The list is:
[1, 2, 3, 4, 5]
The array is:
[1 2 3 4 5]
The data type of array is:
int64
在上面的代码中,我们首先使用array()函数创建了一个 numpy 数组。之后,我们使用 NumPy 数组的dtype属性来获取数组中元素的数据类型。在这里,您可以看到一个整数列表为我们提供了一个数据类型为int64的元素数组。
还可以使用array() 函数中的dtype参数显式指定数组元素的数据类型,如下例所示。
myList=[1,2,3,4,5]
print("The list is:")
print(myList)
myArr = np.array(myList,dtype="float")
print("The array is:")
print(myArr)
print("The data type of array is:")
print(myArr.dtype)
输出:
The list is:
[1, 2, 3, 4, 5]
The array is:
[1\. 2\. 3\. 4\. 5.]
The data type of array is:
float64
在上面的代码中,我们给出了一个整数列表作为输入参数。但是,输出数组包含数据类型为float64的元素,因为我们在创建数组时已经指定了。
要创建一个二维 numpy 数组,您可以将一个列表的列表传递给函数array(),如下所示。
myList=[[1,2,3,4,5],[6,7,8,9,10]]
print("The list is:")
print(myList)
myArr = np.array(myList,dtype="float")
print("The array is:")
print(myArr)
print("The data type of array is:")
print(myArr.dtype)
输出:
The list is:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
The array is:
[[ 1\. 2\. 3\. 4\. 5.]
[ 6\. 7\. 8\. 9\. 10.]]
The data type of array is:
float64
使用不同数据类型的元素创建 Numpy 数组
如果输入列表包含不同但兼容的数据类型的元素,则 numpy 数组中的元素会自动转换为更广泛的数据类型。例如,如果我们有一个 float 和 int 的列表,那么得到的 numpy 数组元素将是 float64 数据类型。您可以在下面的例子中观察到这一点。
myList=[1,3.14,4,5]
print("The list is:")
print(myList)
myArr = np.array(myList)
print("The array is:")
print(myArr)
print("The data type of array is:")
print(myArr.dtype)
输出:
The list is:
[1, 3.14, 4, 5]
The array is:
[1\. 3.14 4\. 5\. ]
The data type of array is:
float64
这里,我们给出了一个包含整数和浮点数的列表。因此,numpy 数组的所有元素都被转换为浮点数。
如果输入列表包含诸如 str 和 int 之类的数据类型,则结果 numpy 数组元素将具有由< u32 或< u64 表示的字符串数据类型。它显示元素分别以 4 字节或 8 字节存储为 unicode 对象。
myList=[1,"Aditya", 3.14,4,5]
print("The list is:")
print(myList)
myArr = np.array(myList)
print("The array is:")
print(myArr)
print("The data type of array is:")
print(myArr.dtype)
输出:
The list is:
[1, 'Aditya', 3.14, 4, 5]
The array is:
['1' 'Aditya' '3.14' '4' '5']
The data type of array is:
<U32
当输入列表元素具有不同的数据类型时,您还可以选择指定数组元素的数据类型。例如,如果您有一个 floats 和 int 的列表,并且您希望数组元素的数据类型是 int,那么您可以在如下所示的dtype参数中指定它。
myList=[1, 3.14,4,5]
print("The list is:")
print(myList)
myArr = np.array(myList,dtype="int")
print("The array is:")
print(myArr)
print("The data type of array is:")
print(myArr.dtype)
输出:
The list is:
[1, 3.14, 4, 5]
The array is:
[1 3 4 5]
The data type of array is:
int64
在这里,您可以观察到具有 float 数据类型的列表元素已经被转换为 int。因此,3.14 已转换为 3。
您还可以将元素转换为其他数据类型,如字符串,如下所示。
myList=[1, 3.14,4,5]
print("The list is:")
print(myList)
myArr = np.array(myList,dtype="str")
print("The array is:")
print(myArr)
print("The data type of array is:")
print(myArr.dtype)
输出:
The list is:
[1, 3.14, 4, 5]
The array is:
['1' '3.14' '4' '5']
The data type of array is:
<U4
在指定数组元素的数据类型时,需要确保输入列表中的所有元素都可以转换为 numpy 数组中指定的数据类型。如果没有发生,程序就会出错。例如,我们不能将字母表转换成整数。因此,如果我们将 numpy 数组的目标数据类型指定为 int,用于包含带有字母的字符串的输入列表,程序将运行到如下所示的 TypeError 异常。
myList=[1,"Aditya", 3.14,4,5]
print("The list is:")
print(myList)
myArr = np.array(myList,dtype="int")
print("The array is:")
print(myArr)
print("The data type of array is:")
print(myArr.dtype)
输出:
The list is:
[1, 'Aditya', 3.14, 4, 5]
ValueError Traceback (most recent call last)
/tmp/ipykernel_4810/3347589872.py in <module>
2 print("The list is:")
3 print(myList)
----> 4 myArr = np.array(myList,dtype="int")
5 print("The array is:")
6 print(myArr)
ValueError: invalid literal for int() with base 10: 'Aditya'
在这个例子中,我们将数组元素的数据类型指定为整数。但是,输入列表包含无法转换为整数的字符串。因此,程序运行到value error int()的无效文字,错误基数为 10 。
在 Python 中检查 Numpy 数组的属性
您可以对 Numpy 数组执行许多操作来检查其属性。例如,您可以使用 numpy 数组的ndim属性来检查数组的维度,如下所示。
myList=[1,"Aditya", 3.14,4,5]
print("The list is:")
print(myList)
myArr = np.array(myList,dtype="str")
print("The array is:")
print(myArr)
print("The dimension of array is:")
print(myArr.ndim)
输出:
The list is:
[1, 'Aditya', 3.14, 4, 5]
The array is:
['1' 'Aditya' '3.14' '4' '5']
The dimension of array is:
1
这里,我们创建了一个一维数组。因此,它的维数是 1。
对于二维列表输入,数组的维数将是 2,如下所示。
myList=[[1,2,3,4,5],[6,7,8,9,10]]
print("The list is:")
print(myList)
myArr = np.array(myList,dtype="str")
print("The array is:")
print(myArr)
print("The dimension of array is:")
print(myArr.ndim)
输出:
The list is:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
The array is:
[['1' '2' '3' '4' '5']
['6' '7' '8' '9' '10']]
The dimension of array is:
2
要检查 numpy 数组中数组元素的数据类型,可以使用dtype属性。属性给出一个dtype对象作为输出。要获得数据类型的名称,您可以使用前面几节已经讨论过的 dtype.name属性。
您还可以使用shape属性找到 numpy 数组的形状。numpy 数组的shape属性返回一个元组,该元组将行数和列数分别作为其第一个和第二个元素。您可以在下面的示例中观察到这一点。
myList=[[1,2,3,4,5],[6,7,8,9,10]]
print("The list is:")
print(myList)
myArr = np.array(myList,dtype="str")
print("The array is:")
print(myArr)
print("The shape of array is:")
print(myArr.shape)
输出:
The list is:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
The array is:
[['1' '2' '3' '4' '5']
['6' '7' '8' '9' '10']]
The shape of array is:
(2, 5)
在这个例子中,我们创建了一个 numpy 数组,它有一个 2-D 列表,有两个内部列表,每个列表包含 5 个元素。因此,numpy 数组的形状是(2,5)。
创建由 0、1 和特定序列组成的 Numpy 数组
使用内置的数组操作,我们可以创建不同类型的 numpy 数组。让我们讨论其中的一些。
在 Python 中创建包含 1 的 Numpy 数组
您可以使用ones() 函数创建包含 1 的 numpy 数组。要使用ones()函数创建一个包含 1 的一维数组,需要将数组中所需元素的数量作为输入参数进行传递。执行后,ones()函数将返回一个一维 numpy 数组,其中包含所需数量的元素,如下所示。
myArr = np.ones(5)
print("The array is:")
print(myArr)
输出:
The array is:
[1\. 1\. 1\. 1\. 1.]
默认情况下,数组中元素的数据类型是 float64。要创建整数数组,可以使用ones()函数的dtype参数来指定元素的数据类型,如下例所示。
myArr = np.ones(5,dtype="int")
print("The array is:")
print(myArr)
输出:
The array is:
[1 1 1 1 1]
在这里,您可以看到数组包含整数作为元素,而不是浮点数。
要使用ones() 函数创建二维数组,可以将一个包含行数和列数的元组以 (number_of_rows, number_of_columns)的格式传递给ones()函数。执行后,ones()函数将返回期望的数组。
myArr = np.ones((2,3),dtype="int")
print("The array is:")
print(myArr)
输出:
The array is:
[[1 1 1]
[1 1 1]]
同样,数组中元素的默认数据类型是float64。因此,您可以使用ones()函数的dtype参数来改变数组元素的数据类型。
在 Python 中创建包含零的 Numpy 数组
就像 1 的数组一样,您也可以使用zeros()函数创建包含 0 的 numpy 数组。
要使用zeros()函数创建一个包含 1 的一维数组,需要将数组中所需元素的数量作为输入参数进行传递。执行后,zeros()函数将返回一个一维 numpy 数组,其中包含所需数量的零,如下所示。
myArr = np.zeros(5)
print("The array is:")
print(myArr)
输出:
The array is:
[0\. 0\. 0\. 0\. 0.]
默认情况下,数组中元素的数据类型是float64。要创建整数数组,可以使用zeros()函数的dtype参数来指定元素的数据类型,如下例所示。
myArr = np.zeros(5,dtype="int")
print("The array is:")
print(myArr)
输出:
The array is:
[0 0 0 0 0]
这里,您可以看到数组包含整数作为其元素,而不是浮点数。
要使用zeros()函数创建二维数组,可以将一个包含行数和列数的元组以(number_of_rows, number_of_columns)的格式传递给zeros()函数。执行后,zeros()函数将返回所需的带零的数组,如下所示。
myArr = np.zeros((2,3),dtype="int")
print("The array is:")
print(myArr)
输出:
The array is:
[[0 0 0]
[0 0 0]]
同样,数组中元素的默认数据类型是float64。因此,您可以使用zeros()函数的dtype参数来改变数组元素的数据类型。
用 0 到 1 之间的随机数创建 Numpy 数组
您可以使用numpy.random.rand()函数创建 numpy 数组,元素范围从 0 到 1。
要创建一维 numpy 数组,可以将所需元素的数量作为输入参数传递给rand()函数。执行后,rand()函数返回一个 numpy 数组,其中包含 0 到 1 之间的指定数量的浮点数。
myArr = np.random.rand(5)
print("The array is:")
print(myArr)
输出:
The array is:
[0.693256 0.26514033 0.86510414 0.52163653 0.1188453 ]
要创建一个二维随机数数组,可以将行数作为第一个输入参数,将所需数组中的列数作为第二个参数。执行后,rand()函数将返回具有所需形状的 numpy 数组,如下所示。
myArr = np.random.rand(2,3)
print("The array is:")
print(myArr)
输出:
The array is:
[[0.03166493 0.06408176 0.73167115]
[0.49889714 0.34302884 0.9395251 ]]
建议阅读:如果你对机器学习感兴趣,并想在这方面进行更多探索,你可以阅读这篇关于机器学习中回归的文章。您可能还会喜欢这篇关于带有数字示例的 k-means 聚类的文章。
用随机整数创建 Numpy 数组
要用一个范围内的随机整数创建一个 numpy 数组,可以使用random.randint() 函数。random.randint()函数的语法如下。
random.randint(start, end, number_of_elements)
这里,
- 参数
start表示范围的起始编号。 - 参数
end表示范围的最后一个数字。 - 参数
number_of_elements表示所需数组中元素的数量。
默认情况下,random.randint()函数返回的数组元素的数据类型是int64。
myArr = np.random.randint(2,100,5)
print("The array is:")
print(myArr)
输出:
The array is:
[22 10 30 87 96]
您不能通过指定dtype参数来使用randint()函数创建浮点数数组。如果你试图这样做,程序将会遇到一个TypeError异常。
用 Python 中的一个范围内的元素创建 Numpy 数组
如果您想创建一个包含某个范围内的元素的 numpy 数组,您可以使用numpy.arange() 函数。
要创建一个元素从 0 到 N 的数组,可以将 N 作为输入参数传递给 arange() 函数。在由arange()函数返回的数组中,你将得到直到 N-1 的数字。这是因为 N 在该范围内是唯一的。
myArr = np.arange(10)
print("The array is:")
print(myArr)
输出:
The array is:
[0 1 2 3 4 5 6 7 8 9]
这里,我们将 10 传递给了arange()函数。因此,它返回了一个包含从 0 到 9 的元素的数组。
要创建一个元素在 M 和 N 之间的 numpy 数组,可以将 M 作为第一个输入参数,将 N 作为第二个输入参数传递给arange()函数。执行后,您将获得一个 numpy 数组,其中包含从 M 到 N-1 的数字。
myArr = np.arange(3,10)
print("The array is:")
print(myArr)
输出:
The array is:
[3 4 5 6 7 8 9]
这里,N 必须大于 m。否则,您将得到一个空数组,如下所示。
myArr = np.arange(13,10)
print("The array is:")
print(myArr)
输出:
The array is:
[]
您还可以决定数组中两个连续元素之间的差异。为此,您可以将所需的数字之差作为第三个输入参数传递给arange() 函数。执行后,它将返回一个 numpy 数组,该数组包含某个范围内的元素以及它们之间的常数差。
myArr = np.arange(3,10,2)
print("The array is:")
print(myArr)
输出:
The array is:
[3 5 7 9]
如果您想获得一个元素降序排列的数组,您可以将一个较大的数字作为第一个输入,将一个较小的数字作为第二个输入参数传递给arange() 函数。作为第三个输入参数,您需要传递一个负数作为两个连续元素之间的差值。这样,您将获得一个 numpy 数组,其中的元素按降序排列,如下例所示。
myArr = np.arange(23,10,-2)
print("The array is:")
print(myArr)
输出:
The array is:
[23 21 19 17 15 13 11]
默认情况下, arange() 函数返回一个以整数为元素的数组。要获得浮点数数组,可以在arange()函数的dtype参数中指定数据类型,如下所示。
myArr = np.arange(23,10,-2,dtype="float")
print("The array is:")
print(myArr)
输出:
The array is:
[23\. 21\. 19\. 17\. 15\. 13\. 11.]
一个范围内所需元素数量的 Numpy 数组
除了决定 numpy 数组中元素的范围之外,还可以指定数组中给定范围内要包含的元素数量。为此,您可以使用linspace()功能。
linspace()函数的语法如下。
linspace(start, end, number_of_elements)
这里,
- 参数
start表示范围的起始编号。 - 参数
end表示范围的最后一个数字。 - 参数
number_of_elements表示所需数组中元素的数量。
默认情况下,linspace()函数返回的数组元素的数据类型是float64。
myArr = np.linspace(2,50,10)
print("The array is:")
print(myArr)
输出:
The array is:
[ 2\. 7.33333333 12.66666667 18\. 23.33333333 28.66666667
34\. 39.33333333 44.66666667 50\. ]
还可以通过向 end 参数传递一个较小的数字,向 start 参数传递一个较大的数字,以逆序获取数组中的元素,如下所示。
myArr = np.linspace(122,50,10)
print("The array is:")
print(myArr)
输出:
The array is:
[122\. 114\. 106\. 98\. 90\. 82\. 74\. 66\. 58\. 50.]
linspace() 函数返回一个浮点数数组。然而,您可以通过使用linspace()函数的dtype参数来创建一个带有整数元素的 numpy 数组。为此,您只需要将文字“int”和其他输入参数一起传递给linspace() 方法中的dtype参数。
在 Python 中将文件加载到 Numpy 数组中
还可以通过加载文本文件来创建 numpy 数组。为此,您可以使用loadtxt() 功能。
loadtxt()函数将文件名作为它的第一个输入参数,将元素的数据类型作为 dtype 参数的输入参数。执行后,它返回一个 numpy 数组,如下所示。
File_data = np.loadtxt("1d.txt", dtype=int)
print(File_data)
输出:
[1 2 3 5 6]
如果输入文件包含除空格和数字以外的字符,程序将会出错。您可以在下面的示例中观察到这一点。
File_data = np.loadtxt("1d.txt", dtype=int)
print(File_data)
输出:
ValueError Traceback (most recent call last)
/tmp/ipykernel_4810/1616002059.py in <module>
----> 1 File_data = np.loadtxt("1d.txt", dtype=int)
2 print(File_data)
ValueError: invalid literal for int() with base 10: '1,2,3,5,6'
您可以通过读取包含二维数据的文件来创建二维 numpy 数组,如下所示。
File_data = np.loadtxt("2d.txt", dtype=int)
print(File_data)
输出:
[[1 2 3]
[4 5 6]
[7 8 9]]
通过观察输出,我们可以推断出loadtxt()函数首先将文件作为字符串读取。之后,它会在新行处分割文件。换行符后的每个字符串都被视为一个新行。然后,它在空格处拆分每一行,以获得 numpy 数组的各个元素。
结论
在本文中,我们讨论了使用 Python 中的 numpy 模块创建数组的不同方法。要了解更多 python 主题,可以阅读这篇关于 Python 中的列表理解的文章。你可能也会喜欢这篇关于如何用 Python 创建聊天应用程序的文章。
用 Python 创建熊猫数据框架
原文:https://www.pythonforbeginners.com/basics/create-pandas-dataframe-in-python
Pandas dataframe 是 Python 中处理表格数据的主要数据结构。在本文中,我们将讨论使用 pandas 模块在 Python 中创建数据帧的不同方法。
在 Python 中创建一个空数据帧
要创建一个空的数据帧,可以使用DataFrame() 功能。在没有任何输入参数的情况下执行时,DataFrame()函数将返回一个没有任何列或行的空数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
myDf=pd.DataFrame()
print(myDf)
输出:
Empty DataFrame
Columns: []
Index: []
要创建具有指定列名的空数据帧,可以使用DataFrame()函数中的 columns 参数。columns参数将一个列表作为其输入参数,并将列表元素分配给 dataframe 的列名,如下所示。
import pandas as pd
myDf=pd.DataFrame(columns=["A", "B", "C"])
print(myDf)
输出:
Empty DataFrame
Columns: [A, B, C]
Index: []
这里,我们创建了一个数据帧,其中包含 A、B 和 C 列,行中没有任何数据。
从字典创建熊猫数据框架
你可以使用DataFrame()函数从 python 字典中创建一个熊猫数据帧。为此,您首先需要创建一个字典列表。之后,您可以将字典列表传递给DataFrame()函数。执行后,DataFrame()函数将返回一个新的数据帧,如下例所示。
import pandas as pd
dict1={"A":1,"B":12,"C":14}
dict2={"A":13,"B":17,"C":12}
dict3={"A":2,"B":11,"C":14}
dictList=[dict1,dict2,dict3]
myDf=pd.DataFrame(dictList)
print(myDf)
输出:
A B C
0 1 12 14
1 13 17 12
2 2 11 14
从字典的列表创建数据帧时,字典的关键字被用作数据帧的列名。如果所有的字典都不包含相同的键,那么对应于一个字典的行将包含列中的NaN值,这些值在字典中不作为键出现。您可以在下面的示例中观察到这一点。
import pandas as pd
dict1={"A":1,"B":12,"C":14}
dict2={"A":13,"B":17,"C":12}
dict3={"A":2,"B":11,"C":14,"D":1117}
dictList=[dict1,dict2,dict3]
myDf=pd.DataFrame(dictList)
print(myDf)
输出:
A B C D
0 1 12 14 NaN
1 13 17 12 NaN
2 2 11 14 1117.0
在这个例子中,第一行和第二行对应于没有 D 作为关键字的字典。因此,这些行包含列 d 中的NaN值。
从 Python 中的系列创建熊猫数据帧
dataframe 由 pandas 系列对象作为其列组成。您也可以将一系列对象的列表传递给DataFrame()函数来创建一个数据帧,如下所示。
series1 = pd.Series([1,2,3])
series2 = pd.Series([4,12,34])
series3 = pd.Series([22,33,44])
seriesList=[series1,series2,series3]
myDf=pd.DataFrame(seriesList)
print(myDf)
输出:
0 1 2
0 1 2 3
1 4 12 34
2 22 33 44
正如您所看到的,series 对象的键标签被转换成数据帧的列。因此,如果作为输入给出的系列对象具有不同的索引标签,则结果数据帧的列名将是所有系列对象的索引标签的并集。此外,数据帧中对应于一个系列的行将包含列中的NaN值,这些值不作为索引标签出现在该系列中。您可以在下面的示例中观察到这一点。
series1 = pd.Series({"A":1,"B":12,"C":14})
series2 = pd.Series({"A":13,"B":17,"C":12})
series3 = pd.Series({"A":2,"B":11,"C":14,"D":1117})
seriesList=[series1,series2,series3]
myDf=pd.DataFrame(seriesList)
print(myDf)
输出:
A B C D
0 1.0 12.0 14.0 NaN
1 13.0 17.0 12.0 NaN
2 2.0 11.0 14.0 1117.0
这里,第一行和第二行对应于没有 D 作为键的序列。因此,这些行包含列 d 中的NaN值。
要数据帧的列表列表
你也可以用 Python 中的列表创建一个数据帧。为此,您可以将列表列表作为输入参数传递给DataFrame()函数,如下所示。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList)
print(myDf)
输出:
0 1 2
0 1 2 3
1 3 55 34
2 12 32 45
在上面的例子中,您可以看到列名和索引都是自动分配的。您还可以观察到,数据帧中行的长度被视为所有列表的长度。如果列表中的元素数量不相等,那么元素数量较少的行将被填充以NaN值,如下所示。
import pandas as pd
list1=[1,2,3,4,55]
list2=[3,55,34]
list3=[12,32,45,32]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList)
print(myDf)
输出:
0 1 2 3 4
0 1 2 3 4.0 55.0
1 3 55 34 NaN NaN
2 12 32 45 32.0 NaN
这里,数据帧中的列数等于输入列表的最大长度。对应于较短列表的行在最右边的列中包含NaN值。
如果您有一个长度相等的列表,您也可以使用DataFrame()函数的columns参数来给 dataframe 指定列名。为此,可以将列名列表传递给 columns 参数,如下例所示。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C"])
print(myDf)
输出:
A B C
0 1 2 3
1 3 55 34
2 12 32 45
在上面的例子中,确保“columns”参数中给定的列数应该大于最大输入列表的长度。否则,程序将会出错。您可以在下面的示例中观察到这一点。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C", "D"])
print(myDf)
输出:
ValueError: 4 columns passed, passed data had 3 columns
在上面的例子中,输入列表的最大长度是 3。但是,我们已经向 columns 参数传递了四个值。因此,程序运行到值错误异常。
用 Python 从 CSV 文件创建数据帧
要从 csv 文件创建熊猫数据帧,您可以使用read_csv()功能。read_csv()函数将 csv 文件的文件名作为其输入参数。执行后,它返回一个 pandas 数据帧,如下所示。
myDf=pd.read_csv("samplefile.csv")
print(myDf)
输出:
Class Roll Name
0 1 11 Aditya
1 1 12 Chris
2 1 13 Sam
3 2 1 Joel
4 2 22 Tom
5 2 44 Samantha
6 3 33 Tina
7 3 34 Amy
创建一个带索引的熊猫数据框架
默认情况下,pandas 数据帧的行使用从 0 开始的整数进行索引。但是,我们可以为数据帧中的行创建自定义索引。为此,我们需要将一个索引名列表传递给函数DataFrame()的 index 参数,如下所示。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C"],index=["a","b","c"])
print(myDf)
输出:
A B C
a 1 2 3
b 3 55 34
c 12 32 45
在这个例子中,我们将列表[a, b, c]传递给了函数DataFrame()的索引参数。执行后,值 a、b 和 c 被分配给行,作为它们在数据帧中的索引。
还可以在创建数据帧后为数据帧中的行创建索引。为此,您可以将索引列表分配给 dataframe 的 index 属性,如下例所示。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C"])
myDf.index=["a","b","c"]
print(myDf)
输出:
A B C
a 1 2 3
b 3 55 34
c 12 32 45
在本例中,我们没有将索引列表传递给 index 参数,而是在创建 dataframe 后将其分配给 dataframe 的 index 属性。
如果从 csv 文件创建数据帧,可以使用如下所示的index_col参数将其中一列指定为索引。
myDf=pd.read_csv("samplefile.csv",index_col="Class")
print(myDf)
输出:
Roll Name
Class
1 11 Aditya
1 12 Chris
1 13 Sam
2 1 Joel
2 22 Tom
2 44 Samantha
3 33 Tina
3 34 Amy
您还可以创建多级索引。为此,您需要将列名列表传递给index_col参数。
myDf=pd.read_csv("samplefile.csv",index_col=["Class","Roll"])
print(myDf)
输出:
Name
Class Roll
1 11 Aditya
12 Chris
13 Sam
2 1 Joel
22 Tom
44 Samantha
3 33 Tina
34 Amy
用 Python 转置熊猫数据帧
我们也可以通过转置另一个数据帧来创建一个熊猫数据帧。为此,您可以使用 T 运算符。在数据帧上调用 T 操作符时,将返回原始 pandas 数据帧的转置,如下所示。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C"])
myDf.index=["a","b","c"]
newDf=myDf.T
print(newDf)
输出:
a b c
A 1 3 12
B 2 55 32
C 3 34 45
在输出中,您可以看到原始数据帧的行变成了新数据帧的列。随后,原始数据帧的列成为新数据帧的索引,反之亦然。
用 Python 复制数据帧
您也可以通过复制现有的数据帧来创建 pandas 数据帧。为此,您可以使用copy()方法。在 dataframe 上调用copy()方法时,会返回一个与原始数据具有相同数据的新 dataframe,如下所示。
import pandas as pd
list1=[1,2,3]
list2=[3,55,34]
list3=[12,32,45]
myList=[list1,list2,list3]
myDf=pd.DataFrame(myList,columns=["A", "B", "C"])
myDf.index=["a","b","c"]
newDf=myDf.copy()
print(newDf)
输出:
A B C
a 1 2 3
b 3 55 34
c 12 32 45
结论
在本文中,我们讨论了用 Python 创建熊猫数据帧的不同方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于如何用 Python 创建聊天应用的文章。您可能也会喜欢这篇关于使用 Python 中的 sklearn 模块进行线性回归的文章。
请继续关注更多内容丰富的文章。
快乐学习!
Python 中的定制 JSON 解码器
原文:https://www.pythonforbeginners.com/basics/custom-json-decoder-in-python
JSON 对象是与 web 应用程序通信的最有效的工具之一。当我们收到一个 JSON 文件时,我们需要将它转换成一个 python 对象,以便在我们的 python 程序中使用。在本文中,我们将讨论在 Python 中创建和使用定制 JSON 解码器的不同方法。
在继续这篇文章之前,如果您不知道如何使用简单的 JSON 对象,我建议您阅读这篇关于在 Python 中使用 JSON 文件的文章。
如何将 JSON 转换成 Python 对象?
您可以使用load()方法、loads()方法或 JSONDecoder 类将 JSON 文件或字符串转换成 python 对象。让我们逐一讨论每种方法。
使用 load()方法将 JSON 文件转换为 Python 对象
load()方法获取一个指向 JSON 文件的文件指针,并返回一个 python 字典对象。例如,我们有下面的 JSON 文件。

JSON object
当我们使用load()方法将这个文件转换成 python 对象时,我们得到一个 python 字典,如下例所示。
import json
fp=open("simplestudent.json")
myDict=json.load(fp)
print("The python object is:")
print(myDict)
输出
The python object is:
{'Name': 'Aditya', 'Age': 23}
如果你想得到一个 python 对象而不是字典,我们需要创建一个定制的 JSON 解码器。为此,我们将创建一个函数,它接受由load()方法返回的字典,并将其转换为 python 对象。我们将在编码 JSON 文件时将函数传递给load()方法中的object_hook参数。您可以在下面的示例中观察到这一点。
import json
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
def SimpleDecoderFunction(jsonDict):
return Student(jsonDict["Name"],jsonDict["Age"])
fp=open("simplestudent.json","r")
python_obj=json.load(fp,object_hook=SimpleDecoderFunction)
print("The python object is:")
print(python_obj)
输出:
The python object is:
<__main__.Student object at 0x7fe1c87a36a0>
在上面的例子中,我们定义了一个Student类。我们还定义了一个SimpleDecoderFunction()函数。当我们在解码 JSON 对象时将SimpleDecoderFunction()传递给load() 方法时,创建的 python 字典对象首先被发送给SimpleDecoderFunction()。SimpleDecoderFunction() 获取字典并将其转换为Student类的 python 对象,我们将该对象作为load()方法的输出。
使用 loads()方法将 Json 字符串转换为 Python 对象
如果有 JSON 字符串而不是 JSON 文件,可以使用loads() 方法将其转换成 python 对象。loads()方法将一个 JSON 字符串作为其输入参数,并返回一个 python 字典,如下例所示。
import json
jsonStr='{"Name": "Aditya", "Age": 23}'
python_obj=json.loads(jsonStr)
print("The python object is:")
print(python_obj)
输出:
The python object is:
{'Name': 'Aditya', 'Age': 23}
要使用loads()方法将 JSON 字符串转换成 python 对象,可以使用定制的 JSON 解码器函数和如下所示的object_hook参数。
import json
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
def SimpleDecoderFunction(jsonDict):
return Student(jsonDict["Name"],jsonDict["Age"])
jsonStr='{"Name": "Aditya", "Age": 23}'
python_obj=json.loads(jsonStr,object_hook=SimpleDecoderFunction)
print("The python object is:")
print(python_obj)
输出:
The python object is:
<__main__.Student object at 0x7fe1c87a17b0>
您可以观察到loads()方法的工作方式与 load()方法相似。唯一的区别是它从字符串而不是文件中读取 JSON 对象。
除了使用load() 方法和loads() 方法,我们还可以使用 JSONDecoder 类创建一个解码器,将 JSON 对象转换成 python 对象。
建议阅读:如果你对机器学习感兴趣,你可以在 mlops for 初学者上阅读这篇文章。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
使用 JSONDecoder 类将 JSON 文件转换为 Python 对象
JSONDecoder 类构造函数具有以下语法
class json.JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
这里,
object_hook参数用于创建定制的 JSON 解码器。object_hook参数将一个函数作为其输入参数。使用从 JSON 解码的对象文字来调用该函数。在输出中,函数的返回值被用来代替字典。parse_float参数用于将 JSON 中的任何浮点数转换成另一种数据类型。默认情况下,解码时用 JSON 中包含浮点数的字符串调用float()函数。如果我们在parse_float参数中指定一个函数,解码器将包含一个浮点数的字符串传递给该函数,该函数的输出在 python 对象中使用。如果您希望在加载 JSON 本身时将浮点转换为 int 或其他数据类型,可以使用这个参数。parse_int参数用于将 JSON 中的任何整数转换成另一种数据类型。默认情况下,使用 JSON 中包含整数的字符串调用int()函数。如果我们在parse_int参数中指定一个函数,解码器将包含整数的字符串传递给该函数,函数的输出在 python 对象中使用。如果您想在加载 JSON 本身时将整数转换成浮点数或其他数据类型,可以使用这个参数。int()的默认parse_int现在通过解释器的整数字符串转换长度限制来限制整数字符串的最大长度,以帮助避免拒绝服务攻击。parse_constant参数用于将NaN、-Infinity和+Infinity从 JSON 加载到自定义 python 值中。parse_constant参数将一个函数作为它的输入参数。而解码器的执行,NaN、-Infinity,和+Infinity被传递给函数,返回值在 python 对象中使用。object_pairs_hook是一个可选参数,它将一个函数作为其输入参数。调用该函数时,任何对象文字的解码结果都带有一个有序的对列表。使用了object_pairs_hook的返回值来代替字典。此功能可用于实现自定义解码器。如果object_hook也被定义,则object_pairs_hook优先。
执行后,JSONDecoder()构造函数返回一个 JSON 解码器。我们可以调用 JSON 解码器上的decode()方法从 JSON 字符串中获取 python 字典,如下所示。
import json
jsonStr='{"Name": "Aditya", "Age": 23}'
print("The JSON string is:")
print(jsonStr)
myDict=json.JSONDecoder().decode(jsonStr)
print("The python object is:")
print(myDict)
输出:
The JSON string is:
{"Name": "Aditya", "Age": 23}
The python object is:
{'Name': 'Aditya', 'Age': 23}
在上面的例子中,我们首先使用JSONDecoder()构造函数创建一个 JSONDecoder 对象。之后,我们调用 JSONDecoder 对象上的 decode()方法。decode()对象接受一个 JSON 字符串作为其输入参数,并返回一个 Python 字典。
要将 JSON 字符串转换成自定义 python 对象,可以在JSONDecoder()构造函数中使用object_hook参数。JSONDecoder() 构造函数接受一个函数作为它的输入参数。该函数必须接受字典,这是解码时的正常输出,并将其转换为自定义 python 对象。例如,考虑下面的例子。
import json
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
def SimpleDecoderFunction(jsonDict):
return Student(jsonDict["Name"],jsonDict["Age"])
jsonStr='{"Name": "Aditya", "Age": 23}'
python_obj=json.JSONDecoder(object_hook=SimpleDecoderFunction).decode(jsonStr)
print("The python object is:")
print(python_obj)
输出:
The python object is:
<__main__.Student object at 0x7fe1c87a32b0>
使用自定义解码器类将嵌套的 JSON 文件转换为 Python 对象
将平面 JSON 文件转换为 python 对象很容易,因为 JSON 对象中的所有值在转换为字典时都是原始数据类型。然而,解码嵌套的 JSON 对象给了我们嵌套的字典。

如果我们将上面的字符串转换成 JSON,我们将得到如下所示的嵌套字典。
import json
jsonStr='{"__type__": "Student","Name": "Aditya", "Age": 23, "Details": {"__type__": "Details","Height": 160, "Weight": 60}}'
python_obj=json.JSONDecoder().decode(jsonStr)
print("The python object is:")
print(python_obj)
输出:
The python object is:
{'__type__': 'Student', 'Name': 'Aditya', 'Age': 23, 'Details': {'__type__': 'Details', 'Height': 160, 'Weight': 60}}
为了将嵌套的 JSON 文件转换成 python 对象,JSON 中应该有一个键-值对来决定我们想要创建的 python 对象的类型。如果 JSON 对象包含要创建的 python 对象的类型,我们可以定义一个自定义函数,该函数获取从 JSON 对象加载的字典,并将其转换为 python 对象。然后,我们将把函数传递给load() 方法中的object_hook参数。此后,load()方法将返回一个定制的 python 对象,而不是一个字典。您可以在下面的示例中观察到这一点。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
def ComplexDecoderFunction(jsonDict):
if '__type__' in jsonDict and jsonDict['__type__'] == 'Student':
return Student(jsonDict['Name'], jsonDict['Age'], jsonDict['Details'])
if '__type__' in jsonDict and jsonDict['__type__'] == 'Details':
return Details(jsonDict['Height'], jsonDict['Weight'])
fp=open("complexstudent.json")
python_obj=json.load(fp,object_hook=ComplexDecoderFunction)
print("The python object is:")
print(python_obj)
fp.close()
输出:
The python object is:
<__main__.Student object at 0x7fe1c87a2d70>
在上面的例子中,我们定义了一个属性为Height和Weight的Details类。我们还用属性Name、Age和Details定义了Student类。
为了将输入嵌套字典转换成 python 对象,我们定义了一个定制的 JSON 解码器函数ComplexDecoderFunction()。输入 json 对象具有属性__type__ 来指定对象可以转换成的 python 对象的类。将复杂的 python 对象编码成 json 的过程将在这篇关于 Python 中的定制 JSON 编码器的文章中讨论。
load() 方法将外部字典和内部字典传递给ComplexDecoderFunction()。该函数使用__type__属性检查字典必须转换到的类,并返回适当类型的 python 对象。然后,load()方法返回完整的 python 对象。
如果想从 json 字符串而不是文件中获取 python 对象,可以使用loads() 方法而不是 load()方法,如下例所示。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
def ComplexDecoderFunction(jsonDict):
if '__type__' in jsonDict and jsonDict['__type__'] == 'Student':
return Student(jsonDict['Name'], jsonDict['Age'], jsonDict['Details'])
if '__type__' in jsonDict and jsonDict['__type__'] == 'Details':
return Details(jsonDict['Height'], jsonDict['Weight'])
jsonStr='{"__type__": "Student","Name": "Aditya", "Age": 23, "Details": {"__type__": "Details","Height": 160, "Weight": 60}}'
python_obj=json.loads(jsonStr,object_hook=ComplexDecoderFunction)
print("The python object is:")
print(python_obj)
输出:
The python object is:
<__main__.Student object at 0x7fe1c87a1f90>
您还可以为嵌套的 json 字符串创建一个定制的解码器,以使用如下所示的JSONDecoder()构造函数创建一个 python 对象。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
def ComplexDecoderFunction(jsonDict):
if '__type__' in jsonDict and jsonDict['__type__'] == 'Student':
return Student(jsonDict['Name'], jsonDict['Age'], jsonDict['Details'])
if '__type__' in jsonDict and jsonDict['__type__'] == 'Details':
return Details(jsonDict['Height'], jsonDict['Weight'])
jsonStr='{"__type__": "Student","Name": "Aditya", "Age": 23, "Details": {"__type__": "Details","Height": 160, "Weight": 60}}'
python_obj=json.JSONDecoder(object_hook=ComplexDecoderFunction).decode(jsonStr)
print("The python object is:")
print(python_obj)
输出:
The python object is:
<__main__.Student object at 0x7fe1c87a31f0>
结论
在本文中,我们讨论了用 python 创建定制 json 解码器的不同方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于如何用 Python 创建聊天应用的文章。您可能也会喜欢这篇关于使用 Python 中的 sklearn 模块进行线性回归的文章。
Python 中的定制 JSON 编码器
原文:https://www.pythonforbeginners.com/basics/custom-json-encoder-in-python
JSON 对象是在互联网上传输信息的最有效的方式之一。但是,我们不能直接将所有类型的数据转换成 JSON。在本文中,我们将讨论创建自定义 JSON 编码器的不同方法,以将 python 对象转换为 Python 中的 JSON 格式。
本文讨论如何用 Python 创建一个定制的 JSON 编码器。如果你没有使用过 JSON 文件,甚至没有使用过默认的编码器,我建议你阅读这篇关于在 Python 中使用 JSON 文件的文章。
使用 dump()方法将 Python 对象转换为 JSON
dump()方法用于将 python 对象转换成 JSON 文件。它接受 python 对象和指向 JSON 文件的文件指针,并将 JSON 格式的内容保存到 JSON 文件中,如下所示。
fp=open("sample.json","w")
myDict={"Name": "Aditya", "Age": 23}
json.dump(myDict, fp)
fp.close()
输出:

这里,我们将 python 字典转换成了 JSON 文件。我们可以使用dump()方法将几乎所有的原始数据类型转换成 JSON 文件。然而,当我们试图使用dump() 方法将自定义 python 对象转换为 JSON 文件时,程序运行到一个类型错误异常,并显示消息“类型错误:type class name 的对象不是 JSON 可序列化的”。
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
student=Student("Aditya",23)
fp=open("sample.json","w")
json.dump(student, fp)
fp.close()
输出:
TypeError: Object of type Student is not JSON serializable
在上面的例子中,我们创建了一个Student类。当我们将一个Student类的 python 对象传递给dump()方法时,程序会遇到 TypeError 异常。这是因为dump()方法不知道如何将 Student 类的对象编码成 JSON 对象。
为了避免这个错误,我们可以在dump()方法中使用“default”参数或“cls”参数。
使用“默认”参数创建定制的 JSON 编码器
当dump()方法获得一个不可序列化的对象作为输入时,它会引发一个 TypeError 异常。您可以使用“default”参数来处理这种情况。default参数将一个函数作为它的输入参数。该函数应该返回对象的 JSON 可序列化版本。
为了创建一个 JSON 可序列化对象,我们将使用对象的__dict__属性将 python 对象转换成它的字典表示。该函数将返回一个可 JSON 序列化的 dictionary 对象。因此,该对象将被转换为 JSON 文件,如下例所示。
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
def SimpleEncoderFunction(obj):
return obj.__dict__
student=Student("Aditya",23)
fp=open("samplestudent.json","w")
json.dump(student, fp,default=SimpleEncoderFunction)
fp.close()
输出:

在上面的例子中,我们定义了一个名为 S impleEncoderFunction()的自定义编码器函数。该函数将 python 对象作为其输入参数,并返回该对象的字典表示。
每当dump()方法遇到不可序列化的定制 python 对象时,它就将该对象发送给 SimpleEncoderFunction。然后,SimpleEncoderFunction()函数将 python 对象转换成字典并返回字典。然后,dump()方法将字典转换成 JSON 格式。
使用“cls”参数创建定制的 JSON 编码器
除了使用默认参数,我们还可以使用cls参数通过dump()方法创建一个定制的 json 编码器。当我们想要将定制的 python 对象转换成 JSON 时,会用到cls参数。为了将自定义对象转换成 JSON,我们需要定义一个自定义 JSONEncoder 子类,并将其传递给cls参数。
子类应该覆盖 JSONEncoder 类的default()方法,并返回 python 对象的 JSON 可序列化版本。例如,考虑下面的例子。
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
class SimpleEncoderClass(json.JSONEncoder):
def default(self, obj):
return obj.__dict__
student=Student("Aditya",23)
fp=open("samplestudent.json","w")
json.dump(student, fp,cls=SimpleEncoderClass)
fp.close()
输出:

这里,SimpleEncoderClass是 JSONEncoder 类的一个子类。它覆盖了default()方法。当我们将SimpleEncoderClass传递给cls参数时,dump() 方法成功地从 python 对象创建了一个 JSON 文件。
在执行过程中,每当dump()方法遇到不可序列化的定制 python 对象时,它就使用SimpleEncoderClass对该对象进行编码。然后,SimpleEncoderClass中的default() 方法将 python 对象转换成字典并返回字典。然后,dump()方法将字典转换成 JSON 格式。
使用 dumps()方法将 Python 对象转换成 JSON
如果想将 python 对象转换成 JSON 字符串而不是 JSON 文件,可以使用dumps()方法。dumps()方法将 JSON 可序列化 python 对象作为其输入参数,并返回 JSON 字符串,如下例所示。
myDict={"Name": "Aditya", "Age": 23}
print("The python object is:")
print(myDict)
jsonStr=json.dumps(myDict)
print("The json string is:")
print(jsonStr)
输出:
The python object is:
{'Name': 'Aditya', 'Age': 23}
The json string is:
{"Name": "Aditya", "Age": 23}
在这个例子中,我们从 python 字典中创建了一个 JSON 字符串。然而,当我们将自定义 python 对象传递给dumps()方法时,它会遇到如下所示的 TypeError 异常。
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
student=Student("Aditya",23)
jsonStr=json.dumps(student)
print("The json string is:")
print(jsonStr)
输出:
TypeError: Object of type Student is not JSON serializable
在这个例子中,您可以观察到dumps()方法无法从类类型Student的 python 对象创建 JSON 字符串。
为了避免这个错误,我们可以将一个定制的 JSON 编码器函数传递给dumps()方法的默认参数,如下所示。
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
def SimpleEncoderFunction(obj):
return obj.__dict__
student=Student("Aditya",23)
jsonStr=json.dumps(student,default=SimpleEncoderFunction)
print("The json string is:")
print(jsonStr)
输出:
The json string is:
{"Name": "Aditya", "Age": 23}
除了默认参数,您还可以对 JSONEncoder 类的子类使用cls参数,如下所示。
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
class SimpleEncoderClass(json.JSONEncoder):
def default(self, obj):
return obj.__dict__
student=Student("Aditya",23)
jsonStr=json.dumps(student,cls=SimpleEncoderClass)
print("The json string is:")
print(jsonStr)
输出:
The json string is:
{"Name": "Aditya", "Age": 23}
在上面的例子中,SimpleEncoderClass和SimpleEncoderFunction使用dumps()方法的方式与使用dump()方法的方式相同。
使用 JSONEncoder 类将 Python 对象转换为 JSON
代替dumps()方法,您可以使用 JSONEncoder 类将 python 对象转换成 JSON 字符串。JSONEncoder 类构造函数具有以下语法。
json.JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
这里,
- python 对象中的键可以是任何数据类型。但是,并非所有的数据类型都可以转换成 JSON 格式。当我们试图用不同于
str、int、float、bool和None的数据类型对 python 对象或字典进行编码时,编码器会引发一个 TypeError 异常。skipkeys参数帮助我们在这种情况下处理数据。当我们将skipkeys设置为True时,编码器会跳过具有不兼容数据类型的键,而不是遇到 TypeError 异常。 ensure_ascii参数用于确保输出 JSON 文件中的所有字符都是 ASCII 字符。当ensure_ascii设置为True时,编码时会跳过所有非 ASCII 字符。如果设置为False,非 ASCII 字符将在编码时保存到 JSON 文件中。check_circular参数用于确保编码器对容器类型执行循环引用检查。如果check_circular被设置为False,循环参考检查被跳过。在这种情况下,循环引用将导致程序运行到 RecursionError。allow_nan参数用于在编码时将NaN和 infinity 值转换为 JSON 格式。当allow_nan设置为True时,编码器将NaN、+inf、-inf分别转换为 JavaScriptNaN、Infinity、-Infinity。当allow_nan设置为False时,编码器在将 python 对象编码为 JSON 时发现NaN、+inf或-inf时,会引发 ValueError 异常。- 如果您希望 JSON 对象的键以一种排序的方式排序,那么在 JSONEncoder 类中使用
sort_keys参数。如果将sort_keys参数设置为True,那么输出 JSON 对象的键将以字典顺序的方式排序。 indent参数用于指定 JSON 对象中的缩进。当 indent 参数设置为None或负整数时,JSON 对象是最紧凑的表示。当indent参数被设置为一个正整数值时,它在编码时创建的 JSON 对象中每层缩进那么多空格。当缩进设置为字符串时,该字符串用作缩进字符。当indent设置为 0 或空字符串时,每缩进一级引入一个新行。- 默认情况下,JSON 对象的键值对由逗号分隔,键和值用冒号分隔。要在将 python 对象编码为 JSON 时为键和项指定新的分隔符,可以将包含两个字符的元组传递给
separators参数。元组的第一个字符成为键和值的分隔符。元组的第二个元素成为不同项目的分隔符。当indent参数设置为None时,separators参数的默认值为(', ', ': ')。否则,separators参数的默认值为(',', ': ')。为了获得最紧凑的 JSON 对象,您应该从分隔符中删除空格,并使用(',', ':')作为separators参数的输入参数。 - 当编码器在 python 对象中获得一个不可序列化的对象时,它会引发一个 TypeError 异常。您可以使用默认参数来处理这种情况。
default参数将一个函数作为其输入参数。该函数应该返回对象的 JSON 可编码版本,或者引发 TypeError。它有助于对无法序列化的 python 对象进行编码。
要将 python 对象转换成 JSON,我们可以首先使用JSONEncoder()构造函数创建一个 JSONEncoder 对象。之后,我们可以调用 JSONEncoder 对象上的encode()方法。encode()方法获取 python 对象并返回一个 JSON 字符串,如下所示。
myDict={"Name": "Aditya", "Age": 23}
print("The python object is:")
print(myDict)
jsonStr=json.JSONEncoder().encode(myDict)
print("The json string is:")
print(jsonStr)
输出:
The python object is:
{'Name': 'Aditya', 'Age': 23}
The json string is:
{"Name": "Aditya", "Age": 23}
在上面的例子中,我们使用 JSONEncoder 类和encode()方法将 python 字典转换为 JSON 字符串。
当我们将一个非 json 可序列化对象传递给encode()方法时,程序会遇到如下所示的 TypeError 异常。
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
student=Student("Aditya",23)
jsonStr=json.JSONEncoder().encode(student)
print("The json string is:")
print(jsonStr)
输出:
TypeError: Object of type Student is not JSON serializable
这里,我们尝试从 Student 类的自定义 python 对象创建一个 JSON 字符串。因为 python 对象是非 json 可序列化的,所以程序运行时遇到了 TypeError 异常。
为了避免错误,我们可以将SimpleEncoderFunction传递给JSONEncoder()构造函数的default参数,如下所示。
class Student:
def __init__(self, name, age):
self.Name=name
self.Age=age
def SimpleEncoderFunction(obj):
return obj.__dict__
student=Student("Aditya",23)
jsonStr=json.JSONEncoder(default=SimpleEncoderFunction).encode(student)
print("The json string is:")
print(jsonStr)
输出:
The json string is:
{"Name": "Aditya", "Age": 23}
这里,JSONEncoder 类使用SimpleEncoderFunction而不是预定义的default() 方法将 python 对象编码成 JSON。
在上面的代码中,每当encode()方法遇到不可序列化的定制 python 对象时,它就将该对象发送给SimpleEncoderFunction。然后SimpleEncoderFunction()函数将 python 对象转换成字典并返回字典。然后,encode()方法将字典转换成 JSON 格式。
建议阅读:如果你对机器学习感兴趣,你可以在 mlops for 初学者上阅读这篇文章。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
JSON 编码器,用于将复杂的 Python 对象转换成 JSON
没有任何其他自定义对象作为其属性的 Python 对象可以很容易地使用简单的 JSON 编码器(如SimpleEncoderFunction或SimpleEncoderClass)转换成 JSON 对象。它们也可以用一个简单的 JSON 解码器转换回 python 对象,正如你在这篇关于 Python 中的定制 JSON 解码器的文章中所看到的。
然而,简单的编码器和解码器不能很好地管理以另一个对象作为其属性的复杂 python 对象。对于复杂的 python 对象,我们可以使用上面讨论过的SimpleEncoderClass或SimpleEncoderFunction。您可以在下面的示例中观察到这一点。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
def SimpleEncoderFunction(obj):
return obj.__dict__
details=Details(160,60)
student=Student("Aditya",23,details)
jsonStr=json.JSONEncoder(default=SimpleEncoderFunction).encode(student)
print("The json string is:")
print(jsonStr)
输出:
The json string is:
{"Name": "Aditya", "Age": 23, "Details": {"Height": 160, "Weight": 60}}
在上面的例子中,我们有一个包含"Height"和"Weight"属性的细节类。在Student类中,我们有"Name"、"Age",和"Details" 属性。
当一个Student类的对象作为输入被提供给encode(方法时,它被发送给SimpleEncoderFunction()。在将学生类转换成字典时,SimpleEncoderFunction() 遇到了Details类。然后,SimpleEncoderFunction() 函数递归调用自己,将Details类的对象作为输入参数。这里,该函数返回一个Details对象的字典表示。然后,SimpleEncoderFunction()返回Student对象的字典表示。之后,字典被encode()方法转换成 JSON 对象。
当我们试图将 JSON 对象转换回 python 对象时,这种类型的编码会导致错误。因此,我们还需要在 JSON 中指定 python 对象的类型。这有助于在解码 JSON 对象时避免错误。
您可以定义一个定制的 JSON 编码器函数,并与如下所示的dump()方法一起使用。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
def ComplexEncoderFunction(obj):
objDict=obj.__dict__
typeDict={"__type__":type(obj).__name__}
return {**objDict,**typeDict}
details=Details(160,60)
student=Student("Aditya",23,details)
fp=open("complexjson.json","w")
json.dump(student, fp,default=ComplexEncoderFunction)
fp.close()
输出:

在上面的例子中,我们定义了一个ComplexEncode rFunction()而不是SimpleEncoderFunction()。在将 python 对象转换为 dictionary 时,ComplexEncoderFunction()添加一个名为"__type__"的键,以 python 对象的类名作为其关联值,然后 dictionary 通过类名转换为 JSON,帮助我们将 JSON 对象转换为具有正确类类型的自定义 python 对象。
您还可以定义一个 JSONEncoder 类的自定义子类,并与如下所示的dump()方法和cls参数一起使用。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
class ComplexEncoderClass(json.JSONEncoder):
def default(self, obj):
objDict=obj.__dict__
typeDict={"__type__":type(obj).__name__}
return {**objDict,**typeDict}
details=Details(160,60)
student=Student("Aditya",23,details)
fp=open("complexjson.json","w")
json.dump(student, fp,cls=ComplexEncoderClass)
fp.close()
输出:

您可以通过如下所示的dumps()方法和default参数使用自定义编码器功能。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
def ComplexEncoderFunction(obj):
objDict=obj.__dict__
typeDict={"__type__":type(obj).__name__}
return {**objDict,**typeDict}
details=Details(160,60)
student=Student("Aditya",23,details)
jsonStr=json.dumps(student,default=ComplexEncoderFunction)
print("The json string is:")
print(jsonStr)
输出:
The json string is:
{"Name": "Aditya", "Age": 23, "Details": {"Height": 160, "Weight": 60, "__type__": "Details"}, "__type__": "Student"}
您还可以通过 dumps()方法使用 JSONEncoder 类的自定义子类,如下所示。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
class ComplexEncoderClass(json.JSONEncoder):
def default(self, obj):
objDict=obj.__dict__
typeDict={"__type__":type(obj).__name__}
return {**objDict,**typeDict}
details=Details(160,60)
student=Student("Aditya",23,details)
jsonStr=json.dumps(student,cls=ComplexEncoderClass)
print("The json string is:")
print(jsonStr)
输出:
The json string is:
{"Name": "Aditya", "Age": 23, "Details": {"Height": 160, "Weight": 60, "__type__": "Details"}, "__type__": "Student"}
除了使用自定义的 JSONEncoder 子类,您还可以使用 JSON encoder 函数和 JSON encoder 构造函数中的default参数来创建 JSON 编码器,并使用它将 python 对象转换为 JSON,如下例所示。
class Student:
def __init__(self, name, age,details):
self.Name=name
self.Age=age
self.Details=details
class Details:
def __init__(self, height, weight):
self.Height=height
self.Weight=weight
def ComplexEncoderFunction(obj):
objDict=obj.__dict__
typeDict={"__type__":type(obj).__name__}
return {**objDict,**typeDict}
details=Details(160,60)
student=Student("Aditya",23,details)
jsonStr=json.JSONEncoder(default=ComplexEncoderFunction).encode(student)
print("The json string is:")
print(jsonStr)
输出
The json string is:
{"Name": "Aditya", "Age": 23, "Details": {"Height": 160, "Weight": 60, "__type__": "Details"}, "__type__": "Student"}
结论
在本文中,我们讨论了创建自定义 JSON 编码器的不同方法,以将复杂的 python 对象转换为 JSON。要了解更多关于 python 编程的知识,你可以阅读这篇关于如何用 Python 创建聊天应用的文章。您可能也会喜欢这篇关于使用 Python 中的 sklearn 模块进行线性回归的文章。
敬请关注更多消息灵通的文章。
快乐学习!
数据营回顾 2021
原文:https://www.pythonforbeginners.com/reviews/datacamp-review
数据科学家是发展最快的职业之一。原因可能是人们被六位数的高薪所吸引,或者他们有数据分析的诀窍,喜欢与大数据打交道。
DataCamp 是数据科学的最佳参考资料来源。这是首个致力于为寻求该主题知识和理解的专业人士提供数据科学培训的在线学习平台。DataCamp 成立于 2014 年,是一个提供 MOOC 的平台。MOOC 代表大规模开放在线课程,意思是该公司专门为世界各地的学生提供在线课程。
在这次 Datacamp 回顾中,我将讲述使用 DataCamp 有多简单,然后谈谈所提供课程的质量。接下来,我将向您介绍 DataCamp 的一些功能,以及在完成定价审查之前,您如何开始免费探索 DataCamp,以及是否值得为 DataCamp 付费。
易用性
当您第一次到达 DataCamp 主页时,您会注意到 DataCamp 是为您学习、实践和参与项目而组织的。一旦您选择了要学习的课程,DataCamp 将为您设置一个仪表盘,屏幕的一半包含说明框,另一半是编码框。说明书教你一门语言的语法,然后给你一些样本代码和一个练习。这里是你练习编码的地方。您在编码框中输入代码,然后您可以运行代码并测试结果,当您对代码感到满意时,您可以提交代码。如果你答对了,你就能获得 XP 点数,否则你会被告知你没有正确编码。
DataCamp 的好处在于它的指令是基于文本和视频驱动的。这在我看来相当令人耳目一新,因为这就像上学一样。有阅读材料和视频形式的讲师指导。
DataCamp 的另一个伟大之处是它会一路测试你。它不是一个编码练习,而是给你一个选择题,你必须选择正确的答案并提交。
课程质量
DataCamp 有 314 门课程,而且这个数字还在稳步增长。至于每门课程的质量,我给它打 9.0 分。我很少给出 10.0 的评分,因为我总是留有改进的空间,对于 DataCamp,我认为质量很好,但并不完美。我认为 DataCamp 的老师可以在每门课程中增加一些真实世界的经验,并给我们一些在真实世界中会看到的问题的想法。我们需要看到在今天的环境中自然发生的现实生活问题,以及如何应用我们的新技能来解决这些问题。
DataCamp 功能
作为一个基于 MOOC 的平台, DataCamp 试图在在线培训方面独树一帜,提供竞争优势。以下是 DataCamp 提供的一些功能:
- 每当您提交练习的正确答案或完成课程时获得的 XP 或经验值。这纯粹是用来激励学习的。
- 没有广告,没有推广,没有干扰。在一门课程中,DataCamp 不会在屏幕上塞满广告或促销活动,否则会分散你的注意力。相反,你会得到一个专注的训练课程。这就像是你和指导老师一对一上课一样。
- 内置解释器。无需在自己的机器上安装软件,因为 DataCamp 提供了一个脚本窗口或编码框,可以在您的浏览器上运行。
- 没有固定的时间表。培训是灵活的,可以根据任何人的时间表量身定制。
数据营定价
DataCamp 面向个人和企业。作为个人,你有三个计划可以选择。从最低级别开始,个人可以免费报名。这是一个很好的开始方式,也是对平台进行测试的一种方式。它将让您访问所有课程,但每个课程只有一个章节。这听起来可能不多,但它会给你一个机会来看看培训的质量,以及 DataCamp 是否适合你。
开始你的 Datacamp 免费试用
下一级是基本计划,每月 25 美元,你可以参加 44 门课程。高级级别每月花费 29 美元,你可以参加超过 314 门课程。不是七个项目,而是八十一个项目。这大大超过了基本水平,而且物有所值。
作为一个企业,有两个计划:专业和企业。专业用户每年每用户 300 美元,企业用户每年每用户 499 美元。这两个计划都可以接触到所有核心课程,并提前接触到新课程。
DataCamp 课程好吗?
每个人都同意,DataCamp 确实擅长提供特定技能的培训,但不擅长传授解决复杂问题所需的批判性思维,或在面临不可预见的挑战时给予数据科学家工作的信心。然而,DataCamp 简化具体性和交互性的方法是创新的。
DataCamp 值得吗?
通过 DataCamp 培训,你将学到成为一名成功的数据科学家所需的技能,但 DataCamp 能帮你找到工作吗?一旦你完成了在 DataCamp 的培训,真正的问题是,成绩声明,data camp 提供的表明你已完成数据科学培训的证书在现实世界中是否有价值?
不幸的是,大多数雇主并不认为这份证书能告诉他们你的技能或能力。这只是表明你从学术角度主动提升了自己,但这并不能证明你是一名专家数据科学家。
如果你寻找的是认证,那么不,DataCamp 不值得。但如果是数据科学培训或为在数据科学领域工作做准备,那么 DataCamp 是你的最佳选择。
Python 中的数据类
原文:https://www.pythonforbeginners.com/basics/dataclass-in-python
在用 python 编程时,您可能已经使用了类来创建不同的对象。python 中的类对于在我们的程序中描述真实世界的物体非常有帮助。在本文中,我们将讨论一个名为 Dataclass 的装饰器,用它我们可以修改一个类的属性。我们还将讨论在用 python 编程时数据类的重要性。
什么是数据类?
Dataclass 是在 dataclasses 模块中定义的装饰器。它是在 python 3.7 中引入的。dataclass decorator 可以用来实现定义只有数据和极少功能的对象的类。
使用 dataclass decorator 定义的类有非常具体的用途和属性,我们将在下面的部分中讨论。让我们首先讨论如何在 python 中使用 dataclass 实现一个类。
Python 中如何使用 dataclass?
dataclass 装饰器已在 dataclasses 模块中定义。您可以首先使用 PIP 安装 dataclasses 模块,如下所示。
pip3 install --upgrade dataclasses
安装 dataclasses 模块后,可以使用 import 语句导入 dataclass 装饰器,如下所示。
from dataclasses import dataclass
现在让我们用 dataclass decorator 定义一个类。
from dataclasses import dataclass
@dataclass
class Person:
Name: str
Country: str
Age: int
candidate = Person("Joe Biden", "USA", 78)
print("The candidate is:",candidate)
输出:
The candidate is: Person(Name='Joe Biden', Country='USA', Age=78)
您可能会注意到,我们在上面的代码中指定了类属性的数据类型。此外,在使用 dataclass 装饰器时,我们不需要实现 init()构造函数。装饰器本身为我们实现了 init()方法。
在 Python 中使用 dataclass 的好处
我们可以使用 dataclass decorator 定义类来表示对象。
如果我们想使用 print 语句打印对象的属性,当我们在没有使用 dataclass decorator 的情况下实现了一个类时,我们必须使用 repr()方法。否则,输出如下。
class Person:
def __init__(self, name, country, age):
self.Name = name
self.Country = country
self.Age = age
candidate = Person("Joe Biden", "USA", 78)
print("The candidate is:", candidate)
输出:
The candidate is: <__main__.Person object at 0x7fb7289a8070>
要打印类属性,我们必须实现 repr()方法,如下所示。
class Person:
def __init__(self, name, country, age):
self.Name = name
self.Country = country
self.Age = age
def __repr__(self):
return "Name: {}, Country: {}, Age: {}".format(self.Name, self.Country, self.Age)
candidate = Person("Joe Biden", "USA", 78)
print("The candidate is:", candidate)
输出:
The candidate is: Name: Joe Biden, Country: USA, Age: 78
但是,当我们使用 dataclass decorator 时,所有的类属性都被打印出来,而没有实现 repr()方法。这可以在下面的例子中观察到。
from dataclasses import dataclass
@dataclass
class Person:
Name: str
Country: str
Age: int
candidate = Person("Joe Biden", "USA", 78)
print("The candidate is:",candidate)
输出:
The candidate is: Person(Name='Joe Biden', Country='USA', Age=78)
简单类和带有 dataclass decorator 的类之间的另一个主要区别是比较类实例的方式。
例如,当我们创建一个类并使用==操作符比较它的实例时,python 解释器检查对象的标识或内存位置,只有当两个实例引用相同的内存位置时,它们才被认为是相等的。这可以在下面的程序中观察到。
class Person:
def __init__(self, name, country, age):
self.Name = name
self.Country = country
self.Age = age
def __repr__(self):
return "Name: {}, Country: {}, Age: {}".format(self.Name, self.Country, self.Age)
candidate1 = Person("Joe Biden", "USA", 78)
candidate2 = Person("Joe Biden", "USA", 78)
print("Candidate 1 is:", candidate1)
print("Candidate 2 is:", candidate2)
print("Both the candidates are same?", candidate1 == candidate2)
输出:
Candidate 1 is: Name: Joe Biden, Country: USA, Age: 78
Candidate 2 is: Name: Joe Biden, Country: USA, Age: 78
Both the candidates are same? False
在这里,您可以看到候选 1 和候选 2 被认为是不同的,因为它们是不同的对象,并且引用不同的内存位置。
相反,当我们使用 dataclass decorator 定义一个类时,比较操作符的工作方式非常不同。当我们使用==操作符比较类的两个实例时,比较的是对象的类属性中的值,而不是内存位置。如果两个实例中相应属性的值相等,则称对象相等。您可以在下面的程序中观察到这一点。
from dataclasses import dataclass
@dataclass
class Person:
Name: str
Country: str
Age: int
candidate1 = Person("Joe Biden", "USA", 78)
candidate2 = Person("Joe Biden", "USA", 78)
print("The candidate 1 is:", candidate1)
print("The candidate 2 is:", candidate2)
print("Both the candidates are same?", candidate1 == candidate2)
输出:
The candidate 1 is: Person(Name='Joe Biden', Country='USA', Age=78)
The candidate 2 is: Person(Name='Joe Biden', Country='USA', Age=78)
Both the candidates are same? True
这里,两个候选对象被认为是相等的,因为对象的属性是相等的。因此,当我们使用 dataclass 装饰器实现类时,我们可以很容易地比较对象内部的数据。
您可以看到 dataclass 装饰器为我们提供了比较对象的更好方法。否则,我们将不得不定义方法来比较对象。这可能导致在时间和空间方面的高成本执行。
结论
在本文中,我们讨论了 python 中的 dataclass 装饰器。我们还实现了它,并看到了它的一些特殊属性,这些属性使它成为我们程序中有用的构造。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
日期和时间脚本
原文:https://www.pythonforbeginners.com/code-snippets-source-code/date-and-time-script
概观
这个脚本可以用来解析日期和时间。打开一个空白文件,将其命名为 dateParser.py。
将下面的代码复制并粘贴到文件中(并确保您理解它的作用)。
dateParser.py
from datetime import datetime
now = datetime.now()
mm = str(now.month)
dd = str(now.day)
yyyy = str(now.year)
hour = str(now.hour)
mi = str(now.minute)
ss = str(now.second)
print mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi + ":" + ss
现在保存并退出该文件,并通过以下方式运行它:
$ python dateParser.py
时间.睡眠
在 Python 中,可以使用 time.sleep()在给定的秒数内暂停执行。括号中给出了秒数。
# How to sleep for 5 seconds in python:
import time
time.sleep(5)
# How to sleep for 0.5 seconds in python:
import time
time.sleep(0.5)
如何获取当前日期和时间
我在这个优秀的网站上找到了这个日期和时间脚本:http://www . salty crane . com/blog/2008/06/how-to-get-current-date-and-time-in/
import datetime
now = datetime.datetime.now()
print
print "Current date and time using str method of datetime object:"
print str(now)
print
print "Current date and time using instance attributes:"
print "Current year: %d" % now.year
print "Current month: %d" % now.month
print "Current day: %d" % now.day
print "Current hour: %d" % now.hour
print "Current minute: %d" % now.minute
print "Current second: %d" % now.second
print "Current microsecond: %d" % now.microsecond
print
print "Current date and time using strftime:"
print now.strftime("%Y-%m-%d %H:%M")
The result:
Current date and time using str method of datetime object:
2013-02-17 16:02:49.338517
Current date and time using instance attributes:
Current year: 2013
Current month: 2
Current day: 17
Current hour: 16
Current minute: 2
Current second: 49
Current microsecond: 338517
Current date and time using strftime:
2013-02-17 16:02
Python 中的十进制模块
原文:https://www.pythonforbeginners.com/basics/decimal-module-in-python
Python 有数字数据类型,如 int、float 和复数,但由于浮点数的机器依赖性,我们需要更精确的数据类型来进行要求高精度的计算。在本文中,我们将研究 python 中的十进制模块,它实现了精度高达 28 位的十进制数。
Python 中什么时候应该用 decimal 代替 float?
Python 将十进制数实现为依赖于机器的双精度浮点数。对于精度因业务原因而至关重要的计算,浮点数在不同的机器上运行时可能会导致错误。因此,对于这样的应用程序,我们需要一个独立于机器的数据类型来实现十进制数,这已经使用 python 中的 decimal 模块实现了。此外,十进制模块实现了精度高达 28 位十进制数的十进制数,而浮点数的精度只有 18 位。这可以在下面的例子中观察到。
import decimal
float_division=4/3
decimal_devision=decimal.Decimal(4)/decimal.Decimal(3)
print("Result for float division of 4 by 3:")
print(float_division)
print("Result for decimal division of 4 by 3:")
print(decimal_devision)
输出:
Result for float division of 4 by 3:
1.3333333333333333
Result for decimal division of 4 by 3:
1.333333333333333333333333333
使用小数而不是浮点数的第二个原因是,在 python 中不能使用数字的精确值来表示数字,而只能使用近似值,这对关键程序来说是危险的。
由于近似值,浮点值对于不同的计算会产生不同的结果。例如,如果我们使用浮点值将 1.2 和 2.2 相加,答案应该等于 3.4。但是当我们把加出来的数和 3.4 比较,就不相等了。出现这种错误是因为浮点数的近似值,1.2 和 2.2 之和不等于 3.4。因此,在需要比较十进制值的情况下,我们应该使用十进制模块,而不是浮点数。从下面的例子可以更清楚地看出这一点。
x=1.2
y=2.2
z=3.4
a=x+y
print("x:",x)
print("y:",y)
print("z:",z)
print("x+y:",a)
print("x+y==z?:",a==z)
输出:
x: 1.2
y: 2.2
z: 3.4
x+y: 3.4000000000000004
x+y==z?: False
Python 中的十进制模块怎么用?
要在 python 中使用 decimal 模块,我们可以如下导入它。
import decimal
导入的模块具有预定义的上下文,其中包含精度、舍入、标志、允许的最小和最大数值的默认值。我们可以使用 getcontext()方法查看上下文的值,如下所示。
import decimal
print(decimal.getcontext())
输出:
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow])
我们还可以设置上下文的精度和其他参数。要将精度从 28 位改为 3 位,我们可以使用下面的程序。
import decimal
decimal.getcontext().prec=3
print(decimal.getcontext())
输出:
Context(prec=3, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow])
默认情况下,在使用小数模块对小数进行舍入时,数字会被均匀地舍入。我们可以通过改变上下文中的“舍入”值来改变这种行为,如下所示。
import decimal
decimal.getcontext().rounding="ROUND_HALF_DOWN"
print(decimal.getcontext())
输出:
Context(prec=3, rounding=ROUND_HALF_DOWN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[InvalidOperation, DivisionByZero, Overflow])
由十进制模块定义的十进制数的所有算术运算都类似于浮点数。差异在于由于实现的不同而导致的值的精度。
舍入值
我们可以使用 round()函数将数字四舍五入到特定的位数。round 函数将需要舍入的十进制数作为第一个参数,将需要舍入的位数作为第二个参数,并返回舍入后的十进制值,如下所示。
import decimal
num1=decimal.Decimal(4)
num2=decimal.Decimal(3)
print("First number is:",num1)
print("Second number is:",num2)
num3=num1/num2
print("num1 divided by num2 is:",num3)
num4=round(num3,2)
print("Rounded value upto two decimal points is:",num4)
输出:
First number is: 4
Second number is: 3
num1 divided by num2 is: 1.333333333333333333333333333
Rounded value upto two decimal points is: 1.33
使用十进制模块比较数字
正如在上面的一节中所看到的,比较浮点数会导致不正确的结果,但是十进制数是精确的,它们的比较总是会得到预期的结果。这可以看如下。
import decimal
x=decimal.Decimal("1.2")
y=decimal.Decimal("2.2")
z=decimal.Decimal("3.4")
a=x+y
print("x:",x)
print("y:",y)
print("z:",z)
print("x+y:",a)
print("x+y==z?:",a==z)
输出:
x: 1.2
y: 2.2
z: 3.4
x+y: 3.4
x+y==z?: True
在上面的代码中,你可以看到我们将字符串转换成了小数,而不是将浮点数转换成了小数。这样做是因为如果我们将浮点数转换为十进制数,近似误差会传播到十进制数,我们将不会得到所需的输出。
结论
在本文中,我们研究了使用浮点数进行算术运算的缺点,并使用十进制模块在 python 中实现了相同的运算,并且没有错误。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
德尔声明
del 语句可以通过引用索引而不是值来从列表中删除一个项目。例如,如果您有一个包含五个值的列表,如下所示:
a = [1, 2, 3, 4, 5]
并且您想要删除第二个列出的值(2),您可以使用 del 来执行此操作。第二个列出的值的索引为 1,因此要删除该值,del 语法需要如下所示:
del a[1]
现在 a 看起来像这样:
a = [1, 3, 4, 5]
在 Python 中删除列表的所有元素
原文:https://www.pythonforbeginners.com/basics/delete-all-elements-of-a-list-in-python
在 python 中,我们几乎在每个程序中都使用列表。我们已经讨论了在 python 中比较两个列表和反转列表的方法。在本文中,我们将讨论在 python 中删除列表中所有元素的不同方法。
使用 clear()方法删除 Python 中列表的所有元素
pop()方法用于删除列表中的最后一个元素。当在列表上调用时,pop()方法返回列表的最后一个元素,并将其从列表中删除。我们可以使用 while 循环和 pop()方法来删除列表中的所有元素。
为此,我们可以在 while 循环中继续调用列表上的 pop()方法,直到列表变空。一旦列表变空,while 循环将停止执行,我们将得到一个没有元素的列表。您可以在下面的程序中观察到这一点。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:")
print(myList)
# deleting elements using the pop() method
while myList:
myList.pop()
print("List after deleting all the elements:",myList)
输出:
The original list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting all the elements: []
我们可以使用 clear()方法删除列表中的所有元素,而不是多次使用 pop()方法。当在列表上调用 clear()方法时,会删除列表中的所有元素。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:")
print(myList)
# deleting elements using the clear() method
myList.clear()
print("List after deleting all the elements:",myList)
输出:
The original list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting all the elements: []
使用 del 语句删除 Python 中列表的所有元素
del 语句用于删除 python 中的对象。我们还可以使用 del 语句删除列表中的元素。为此,我们将创建一个包含所有元素的列表片段。之后,我们将删除切片。由于切片包含对原始列表中元素的引用,原始列表中的所有元素都将被删除,我们将得到一个空列表。你可以这样做。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:")
print(myList)
# deleting elements using the del method
del myList[:]
print("List after deleting all the elements:", myList)
输出:
The original list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting all the elements: []
使用*运算符删除 Python 中列表的所有元素
这是 Python 中最少使用的从列表中移除元素的方法之一。你可能知道,将一个列表乘以任意数 N 会将列表中的元素重复 N 次。同样的,当我们将一个列表乘以 0 时,列表中的所有元素都会被删除。因此,我们可以将给定的列表乘以 0,以删除它的所有元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:")
print(myList)
# deleting elements using *
myList = myList * 0
print("List after deleting all the elements:", myList)
输出:
The original list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting all the elements: []
结论
在本文中,我们讨论了用 python 删除列表中所有元素的四种不同方法。要了解更多关于 python 中的列表,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于如何用 python 获得列表的最后一个元素的文章。
在 Python 中删除对象的属性
原文:https://www.pythonforbeginners.com/basics/delete-attribute-from-an-object-in-python
Python 是一种面向对象的编程语言。我们经常在编程时使用用自定义类定义的对象。在本文中,我们将讨论如何在 Python 中删除对象的属性。
使用 Python 中的 del 语句从对象中删除属性
del 语句可以用来删除任何对象及其属性。del语句的语法如下。
del object_name
为了查看如何从对象中删除属性,让我们首先创建一个定制类Person,它具有属性name、age、SSN和weight。
class Person:
def __init__(self, name, age, SSN, weight):
self.name = name
self.age = age
self.SSN = SSN
self.weight = weight
现在我们将创建一个名为Person类的对象person1。之后,我们将使用如下所示的del语句从person1对象中删除属性weight。
class Person:
def __init__(self, name, age, SSN, weight):
self.name = name
self.age = age
self.SSN = SSN
self.weight = weight
def __str__(self):
return "Name:" + str(self.name) + " Age:" + str(self.age) + " SSN: " + str(self.SSN) + " weight:" + str(
self.weight)
person1 = Person(name="Will", age="40", SSN=1234567890, weight=60)
print(person1)
del person1.weight
print(person1)
输出:
Name:Will Age:40 SSN: 1234567890 weight:60
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 16, in <module>
print(person1)
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 10, in __str__
self.weight)
AttributeError: 'Person' object has no attribute 'weight'
在上面的例子中,你可以看到我们可以在执行del语句之前打印属性weight。当我们在执行完del语句后试图打印属性weight时,程序遇到了AttributeError异常,称对象中没有名为weight的属性。因此,我们已经使用 python 中的del语句成功地从对象中删除了属性。
使用 Python 中的 delattr()函数从对象中删除属性
我们还可以使用 delattr()函数从对象中删除属性。delattr()函数接受一个对象作为它的第一个输入参数,属性名作为它的第二个输入参数。执行后,它从给定对象中删除属性。您可以在下面的示例中观察到这一点。
class Person:
def __init__(self, name, age, SSN, weight):
self.name = name
self.age = age
self.SSN = SSN
self.weight = weight
def __str__(self):
return "Name:" + str(self.name) + " Age:" + str(self.age) + " SSN: " + str(self.SSN) + " weight:" + str(
self.weight)
person1 = Person(name="Will", age="40", SSN=1234567890, weight=60)
print(person1)
delattr(person1, "weight")
print(person1)
输出:
Name:Will Age:40 SSN: 1234567890 weight:60
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 16, in <module>
print(person1)
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 10, in __str__
self.weight)
AttributeError: 'Person' object has no attribute 'weight'
您可以看到,我们能够在执行delattr() 函数之前打印出person1对象的weight属性。在执行了delattr()函数后,当我们试图打印person1对象的weight属性时,程序引发了AttributeError异常,表示该属性已被删除。
如果我们传递一个对象中不存在的属性名,它会引发如下所示的AttributeError异常。
class Person:
def __init__(self, name, age, SSN, weight):
self.name = name
self.age = age
self.SSN = SSN
self.weight = weight
def __str__(self):
return "Name:" + str(self.name) + " Age:" + str(self.age) + " SSN: " + str(self.SSN) + " weight:" + str(
self.weight)
person1 = Person(name="Will", age="40", SSN=1234567890, weight=60)
print(person1)
delattr(person1, "BMI")
print(person1)
输出:
Name:Will Age:40 SSN: 1234567890 weight:60
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn't match a supported version!
warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 15, in <module>
delattr(person1, "BMI")
AttributeError: BMI
在这里,您观察到我们试图从对象中不存在的person1对象中删除BMI属性。因此,程序遇到了AttributeError异常。
结论
在本文中,我们讨论了在 python 中从对象中删除属性的两种方法。要了解关于对象和类的更多信息,您可以阅读这篇关于 python 中的类的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
建议阅读:
Python 中的深度优先遍历
原文:https://www.pythonforbeginners.com/data-structures/depth-first-traversal-in-python
图形是非线性数据结构,用于表示不同对象之间的关系。在本文中,我们将讨论深度优先遍历算法来打印图中的顶点。我们还将在 python 中实现深度优先遍历算法,以说明该算法的工作原理。
什么是深度优先遍历?
深度优先遍历是一种图遍历算法,我们从图的一个顶点开始,打印出它的值。然后我们移动到当前顶点的一个邻居并打印它的值。如果当前顶点没有必须打印的相邻顶点,我们就移动到前一个顶点,看看是否打印了它们的所有相邻顶点。如果没有,我们选择一个邻居并打印它的值。我们重复这个过程,直到图形的所有顶点都打印出来。应该注意的是,我们只需打印每个顶点一次。
让我们在下图中尝试这个过程。

Graph
这里,让我们从顶点 a 开始。首先,我们将打印 a。之后,我们将从 B、D、E 和 F 中选择一个顶点,因为它们都是 a 的邻居。
让我们选择 B。在打印 B 之后,我们将从 A、C 和 F 中选择一个顶点,因为它们是 B 的邻居。这里,A 已经被打印,所以不会被选择。
让我们选择 C。在打印 C 之后,我们没有 C 的邻居要打印。因此,我们将移动到 C 的前一个顶点,即顶点 B,以检查是否已经打印了 B 的所有邻居。这里,F 还没有打印出来。所以我们会选择 f。
打印 F 之后,我们必须从 A 和 B 中选择一个顶点,因为它们是 F 的邻居,但是这两个顶点都已经打印出来了。因此,我们将移动到前一个顶点。
在 B 处,我们可以看到 B 的所有邻居都已经被打印了。因此,我们将移动到 B 的前一个顶点,即 a。
在 A 处,邻居 D 和 E 尚未打印,因此我们将选择其中一个顶点。
让我们选择 D。在打印 D 之后,我们可以看到 D 没有任何邻居要打印。因此,我们将移动到它的前一个顶点,即 a。
现在,只有 A 的一个邻居没有被打印,也就是说,我们将打印 e。
此时,图形的所有顶点都已按照 A、B、C、F、D、e 的顺序打印出来。因此,我们将停止这一过程。
您可以观察到,基于我们选择的邻居,单个图可能有许多深度优先遍历。
深度优先遍历算法
使用一个堆栈数据结构来实现图的深度优先遍历算法。这里,我们假设我们有一个连通图。换句话说,我们可以从起始顶点到达图的每个顶点。
我们将维护一个堆栈来存储未打印的顶点,并维护一个列表来存储已访问的顶点。之后,我们将使用以下算法处理该图。
- 创建一个空栈来存储没有被打印的顶点。
- 创建一个空列表 L 来存储访问过的顶点。
- 将源顶点插入到 s 中,同样,将源顶点插入到 l 中。
- 如果堆栈 S 为空,转到 9,否则转到 5。
- 从 s 中取出一个顶点 v。
- 打印以 v 为单位的值。
- 将 v 的所有未访问的邻居插入堆栈 S 和列表 l。
- 转到第 4 节。
- 停下来。
可以使用上图中给出的图形的源代码来演示该算法。
graph = {'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
print("Given Graph is:")
print(graph)
def DFS_Algorithm(input_graph, source):
stack = list()
visited_list = list()
print("At {}, adding vertex {} to stack and visited list".format(source, source))
stack.append(source)
visited_list.append(source)
while stack:
vertex = stack.pop()
print("At vertex :", vertex)
print("Printing vertex:", vertex)
for u in input_graph[vertex]:
if u not in visited_list:
print("At {}, adding vertex {} to stack and visited list".format(vertex, u))
stack.append(u)
visited_list.append(u)
print("Vertices in visited list are:", visited_list)
print("Vertices in stack are:", stack)
print("Explanation of DFS traversal of graph with source A is:")
DFS_Algorithm(graph, "A")
输出:
Given Graph is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
Explanation of DFS traversal of graph with source A is:
At A, adding vertex A to stack and visited list
At vertex : A
Printing vertex: A
At A, adding vertex B to stack and visited list
At A, adding vertex D to stack and visited list
At A, adding vertex E to stack and visited list
At A, adding vertex F to stack and visited list
Vertices in visited list are: ['A', 'B', 'D', 'E', 'F']
Vertices in stack are: ['B', 'D', 'E', 'F']
At vertex : F
Printing vertex: F
Vertices in visited list are: ['A', 'B', 'D', 'E', 'F']
Vertices in stack are: ['B', 'D', 'E']
At vertex : E
Printing vertex: E
Vertices in visited list are: ['A', 'B', 'D', 'E', 'F']
Vertices in stack are: ['B', 'D']
At vertex : D
Printing vertex: D
Vertices in visited list are: ['A', 'B', 'D', 'E', 'F']
Vertices in stack are: ['B']
At vertex : B
Printing vertex: B
At B, adding vertex C to stack and visited list
Vertices in visited list are: ['A', 'B', 'D', 'E', 'F', 'C']
Vertices in stack are: ['C']
At vertex : C
Printing vertex: C
Vertices in visited list are: ['A', 'B', 'D', 'E', 'F', 'C']
Vertices in stack are: []
在输出中,您可以观察到所有顶点最终都出现在已访问列表中,并且它们按照 A、F、E、D、B、c 的顺序打印。您可以看到顶点的顺序与我们在上一节中讨论的顺序不同。这是因为当我们选择一个顶点的邻居时,我们有许多选项可以选择,并且顺序取决于我们选择的顶点。
深度优先遍历在 Python 中的实现
我们已经讨论了图的深度优先遍历的一般思想,并观察了该算法如何使用 python 程序工作,我们可以如下实现深度优先遍历算法。
graph = {'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
print("Given Graph is:")
print(graph)
def dfs_traversal(input_graph, source):
stack = list()
visited_list = list()
stack.append(source)
visited_list.append(source)
while stack:
vertex = stack.pop()
print(vertex, end=" ")
for u in input_graph[vertex]:
if u not in visited_list:
stack.append(u)
visited_list.append(u)
print("DFS traversal of graph with source A is:")
dfs_traversal(graph, "A")
输出:
Given Graph is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
DFS traversal of graph with source A is:
A F E D B C
结论
在本文中,我们讨论了全连通图的深度优先遍历算法,并且用 Python 实现了它。在我们的实现中,我们使用了一个列表作为堆栈,但是堆栈也可以使用 Python 中的链表来实现。要了解更多关于其他算法的内容,您可以阅读这篇关于 Python 中的有序树遍历的文章。
python
双端队列是线性数据结构,我们可以用它来执行后进先出(LIFO)操作和先进先出(FIFO)操作。Deques 在现实生活中有很多应用,比如在软件中实现撤销操作,在 web 浏览器中存储浏览历史。在本文中,我们将研究 deque 背后的基本概念,并用 python 实现它们。
如何用 python 实现 deque?
如上所述,deques 是线性数据结构。因此,我们可以使用 python 中的 list 实现 deque。要使用 list 实现 deque,我们必须在 list 的两边插入和删除元素。我们还可以执行像检查队列长度或检查队列是否为空这样的操作。对于这个任务,我们将使用一个 dequeSize 方法来记录 deque 中元素的数量。可以使用下面的类定义在 python 中实现 dequeue,其中我们定义了一个名为 dequeList 的空列表来初始化空 dequeue,并将 dequeSize 初始化为 0,如下所示。
class Deque:
def __init__(self):
self.dequeList=list()
self.dequeSize=0
python 中 deque 中的插入
我们可以在队列的前面和后面插入一个元素。要在 deque 的前面插入一个元素,我们只需使用 insert()方法在 dequeList 的开头插入该元素。然后我们将把 dequeSize 增加 1。这可以如下进行。
def insertAtFront(self,data):
self.dequeList.insert(0,data)
self.dequeSize=self.dequeSize+1
要在 deque 的后面插入一个元素,我们将使用 append()方法将该元素附加到 dequeList 的末尾,然后将 dequeSize 增加 1。这可以如下进行。
def insertAtRear(self,data):
self.dequeList.append(data)
self.dequeSize=self.dequeSize+1
在 python 中从队列中删除元素
我们可以从队列的前面和后面删除一个元素。在删除一个元素之前,我们将首先检查队列是否为空,并将使用 python try except 抛出一个异常,即队列为空。否则,我们将继续从队列中删除该元素。
要删除 dequeue 前面的元素,我们将使用 pop()方法删除 dequeList 的第一个元素,然后将 dequeSize 减 1。这可以如下进行。
def deleteFromFront(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
self.dequeList.pop(0)
self.dequeSize=self.dequeSize-1
except Exception as e:
print(str(e))
为了从 deque 的后面删除一个元素,我们将删除 dequeList 的最后一个位置的元素,并将 dequeSize 减 1。这可以如下进行。
def deleteFromRear(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
self.dequeList.pop(-1)
self.dequeSize=self.dequeSize-1
except Exception as e:
print(str(e))
检查队列的长度
要检查 dequee 的长度,我们只需检查 dequee 的 dequeSize 字段中的值,该字段保存了 dequee 的长度。我们可以实现 length()方法来检查 python 中 deque 的长度,如下所示。
def dequeLength(self):
return self.dequeSize
检查队列是否为空
要检查 deque 是否为空,我们只需检查 dequeSize 字段中是否有值 0。我们可以用 python 实现一个方法 isEmpty()来检查队列是否为空,如下所示。
def isEmpty(self):
if self.dequeSize==0:
return True
return False
检查前后元件
为了检查 deque 的 front 元素,我们可以如下实现 front()方法。
def front(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
return self.dequeList[0]
except Exception as e:
print(str(e))
为了检查 deque 的尾部元素,我们可以如下实现 rear()方法。
def rear(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
return self.dequeList[-1]
except Exception as e:
print(str(e))
下面是 python 中使用 list 的 deque 的完整实现。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 3 18:31:28 2021
@author: aditya1117
"""
class Deque:
def __init__(self):
self.dequeList=list()
self.dequeSize=0
def isEmpty(self):
if self.dequeSize==0:
return True
return False
def dequeLength(self):
return self.dequeSize
def insertAtFront(self,data):
self.dequeList.insert(0,data)
self.dequeSize=self.dequeSize+1
def insertAtRear(self,data):
self.dequeList.append(data)
self.dequeSize=self.dequeSize+1
def deleteFromFront(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
self.dequeList.pop(0)
self.dequeSize=self.dequeSize-1
except Exception as e:
print(str(e))
def deleteFromRear(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
self.dequeList.pop(-1)
self.dequeSize=self.dequeSize-1
except Exception as e:
print(str(e))
def front(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
return self.dequeList[0]
except Exception as e:
print(str(e))
def rear(self):
try:
if self.dequeSize==0:
raise Exception("Deque is Empty")
else:
return self.dequeList[-1]
except Exception as e:
print(str(e))
结论
在本文中,我们研究了 deque 背后的概念,并使用 python 中的 list 实现了它。为了更深入地了解它,并理解 dequee 与内置数据结构(如 python dictionary 、list 和 set)有何不同,复制上面示例中给出的完整代码,将其粘贴到您的 IDE 中,并试验 dequee 操作。请继续关注更多内容丰富的文章。


浙公网安备 33010602011771号