PythonForBeginners-中文系列教程-四-
PythonForBeginners 中文系列教程(四)
Python 中的递归
原文:https://www.pythonforbeginners.com/basics/recursion-in-python
你可能学过 python 中的函数。在 Python 中编程时,您可能还使用了 for 循环和 while 循环来重复执行任务。在本文中,我们将讨论 Python 中的递归和递归函数。
什么是递归?
递归是一个数学概念,在这个概念中,我们根据事物本身来定义它。
例如,我们可以将前十个自然数的和定义为前九个自然数加上第十个自然数的和。
同样,我们可以把前九个自然数之和定义为前八个自然数加上第九个自然数之和。
在这里,你可以看到我们把前十个自然数的问题分解成更小的问题,比如求前 9 个数的和,然后求前 8 个数的和,等等。这样,我们将到达一个位置,我们必须找到第一个自然数的和,即 1 本身。在此之后,我们将只执行原子加法,而不用担心我们正在寻找的自然数的总数。
Python 中什么时候使用递归?
如上所述,每当我们可以将一个问题分解成一个相似但更小的问题时,我们就可以使用递归。我们使用递归时最常见的问题是:
- 二叉树遍历问题
- 求一个数的阶乘
- 汉诺塔问题
- 寻找斐波那契数列
Python 中如何使用递归?
在编程中,如果一个函数调用它自己,我们说它是一个递归函数,也就是说它是基于递归的概念工作的。您可以在 python 中使用递归来实现任何问题的解决方案,这些问题可以简化为一个类似但更小的问题。
例如,让我们试着找出前 10 个自然数的和。为此,让我们定义一个 sumOfNumbers()函数,它接收一个输入数字 N,并返回从 1 到 N 的数字之和。
- 为了计算前 10 个自然数的和,即 sumOfNumbers(10),我们将找到前 9 个自然数的和,即 sumOfNumbers(9),并将它加上 10。
- 类似地,为了找到前 9 个自然数的和,即 sumOfNumbers(9),我们将找到前 8 个自然数的和,即 sumOfNumbers(8),并将在其上加上 9。
- 同样,为了求出前 8 个自然数的和,即 sumOfNumbers(8),我们将求出前 7 个自然数的和,即 sumOfNumbers(7),并将它加上 8。
- 之后,要找到前 7 个自然数的和,即 sumOfNumbers(7),我们将找到前 6 个自然数的和,即 sumOfNumbers(6),并将它加上 7。
- 这样,我们将达到必须计算第一个自然数的和,即 sumOfNumbers(1)的位置。在这里,我们可以简单地返回 1。这也称为递归的基本情况,因为问题不能进一步简化成更小的问题。
我们可以如下实现上述算法。
def sumOfNumbers(N):
if N == 1:
return N
else:
return N + sumOfNumbers(N - 1)
input_number = 10
output = sumOfNumbers(input_number)
print("Sum of first {} natural numbers is {}".format(input_number, output))
input_number = 20
output = sumOfNumbers(input_number)
print("Sum of first {} natural numbers is {}".format(input_number, output))
输出:
Sum of first 10 natural numbers is 55
Sum of first 20 natural numbers is 210
使用递归时,我们必须指定基本情况。否则,程序将继续不断地执行,并运行到 RecursionError。这是因为在 Python 中,一个函数可以进行的最大递归调用次数被限制在 1000 次。如果任何函数进行的递归调用超过 1000 次,就会出现 RecursionError 异常。
结论
在本文中,我们讨论了 python 中的递归。我们还实现了一个程序,用 Python 计算前 10 个自然数的总和。要了解关于函数的更多信息,您可以阅读这篇关于 python 中的闭包的文章。
Python 代码:从一个网站获取所有链接
原文:https://www.pythonforbeginners.com/code/regular-expression-re-findall
概观
In this script, we are going to use the re module to get all links from any website.
One of the most powerful function in the re module is "re.findall()".
While re.search() is used to find the first match for a pattern, re.findall() finds *all*
the matches and returns them as a list of strings, with each string representing one match.
从网站获取所有链接
This example will get all the links from any websites HTML code.
To find all the links, we will in this example use the urllib2 module together
with the re.module
import urllib2
import re
#connect to a URL
website = urllib2.urlopen(url)
#read html code
html = website.read()
#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)
print links
Happy scraping!
Python 中的正则表达式
原文:https://www.pythonforbeginners.com/regex/regular-expressions-in-python
什么是正则表达式?
这是一个用紧凑语法编写的字符串模式,允许我们快速检查
给定的字符串是否匹配或包含给定的模式。
正则表达式的强大之处在于它们可以指定模式,而不仅仅是
固定字符。这篇文章中的许多例子可以在:
谷歌 Python 课程上找到
基本模式
a,X,9
普通人物正好和自己完全匹配。
。^ $ * + ?{ [ ] | ( )
具有特殊含义的元字符(见下文)
。
(句点)匹配除换行符' n '以外的任何单个字符
w
匹配一个“单词”字符:一个字母或数字或下划线[a-zA-Z0-9_]。
它只匹配单个字符,而不是整个单词。
W
匹配任何非单词字符。
w+
匹配一个或多个单词/字符
b
词与非词的界限
s
匹配单个空白字符、空格、换行符、回车符、制表符、表单
S
匹配任何非空白字符。
t,n,r
制表符、换行符、回车
D
匹配除了数字以外的任何东西
d
匹配一个十进制数字[0-9]
d{1,5}
匹配长度在 1 到 5 之间的数字。
{n} d{5}
连续匹配 5 位数
匹配字符串的开始
$
匹配字符串结束的
匹配 0 个或更多重复**
?
匹配其前面的 0 或 1 个字符
使用。匹配句点或匹配斜杠。
如果您不确定某个字符是否有特殊含义,例如' @ ',您可以
在它前面加上一条斜线@以确保它被视为一个字符。
重新发现
findall()可能是 re 模块
中最强大的函数,我们将在这个脚本中使用这个函数。
在下面的例子中,我们创建了一个包含许多电子邮件地址的字符串。
然后我们创建一个变量(emails ),它将包含所有找到的
电子邮件字符串的列表。
最后,我们使用一个 for 循环,我们可以对找到的每个电子邮件字符串
做一些事情。
`str = 'purple [[email protected]](/cdn-cgi/l/email-protection), blah monkey [[email protected]](/cdn-cgi/l/email-protection) blah dishwasher'
## Here re.findall() returns a list of all the found email strings
emails = re.findall(r'[w.-][[email protected]](/cdn-cgi/l/email-protection)[w.-]+', str) ## ['[[email protected]](/cdn-cgi/l/email-protection)', '[[email protected]](/cdn-cgi/l/email-protection)']
for email in emails:
# do something with each found email string
print email`
我们也可以将此应用于文件。如果您有一个文件,并且想要遍历该文件的所有行,只需将它输入 findall()并让它在一个步骤中返回一个包含所有匹配的列表
read()在单个字符串中返回文件的全部文本。
(如果你想了解更多关于 Python 中的文件处理,我们写了一个
‘备忘单’,你可以在这里找到)
`# Open file
f = open('test.txt', 'r')
# Feed the file text into findall(); it returns a list of all the found strings
strings = re.findall(r'some pattern', f.read())`
重新搜索
re.search()方法接受一个正则表达式模式和一个字符串,然后
在字符串中搜索该模式。
语法是 re.search(模式,字符串)。
其中:
模式
要匹配的正则表达式。
字符串
将被搜索以匹配字符串中任何位置的模式的字符串。
它在带有可选标志的字符串中搜索第一个出现的 RE 模式。
如果搜索成功,search()返回一个匹配对象,否则返回 None。
因此,搜索之后通常会立即跟随一个 if 语句来测试
搜索是否成功。
在模式字符串的开头使用“r”是很常见的,这表示
一个 python“原始”字符串,它通过反斜杠而不改变,这对于正则表达式来说
非常方便。
此示例搜索模式“word:”后跟一个 3 个字母的单词。
代码 match = re.search(pat,str)将搜索结果存储在名为“match”的变量
中。
然后,if 语句测试匹配,如果为真,则搜索成功,并且
match.group()是匹配的文本(例如‘word:cat’)。
如果匹配为 false,则搜索没有成功,并且没有匹配的文本。
`str = 'an example word:cat!!'
match = re.search(r'word:www', str)
# If-statement after search() tests if it succeeded
if match:
print 'found', match.group() ## 'found word:cat'
else:
print 'did not find'`
正如您在下面的例子中看到的,我使用了|操作符,它搜索我指定的模式。
`import re
programming = ["Python", "Perl", "PHP", "C++"]
pat = "^B|^P|i$|H$"
for lang in programming:
if re.search(pat,lang,re.IGNORECASE):
print lang , "FOUND"
else:
print lang, "NOT FOUND"`
上述脚本的输出将是:
Python 找到了
Perl 找到了
PHP 找到了
C++没有找到
再接
re 模块中的 re.sub()函数可用于替换子字符串。
re.sub()的语法是 re.sub(pattern,repl,string)。
这将用 repl 替换字符串中的匹配项。
在这个例子中,我将用 repl ("good ")替换 string (text)中所有出现的 re 模式(" cool")
。
`import re
text = "Python for beginner is a very cool website"
pattern = re.sub("cool", "good", text)
print text2`
这是另一个例子(取自谷歌的 Python 类),它搜索所有
的电子邮件地址,并更改它们以保留用户(1)但将
yo-yo-dyne.com 作为主机。
`str = 'purple [[email protected]](/cdn-cgi/l/email-protection), blah monkey [[email protected]](/cdn-cgi/l/email-protection) blah dishwasher'
## re.sub(pat, replacement, str) -- returns new string with all replacements,
## 1 is group(1), 2 group(2) in the replacement
print re.sub(r'([w.-]+)@([w.-]+)', r'[[email protected]](/cdn-cgi/l/email-protection)', str)
## purple [[email protected]](/cdn-cgi/l/email-protection), blah monkey [[email protected]](/cdn-cgi/l/email-protection) blah dishwasher`
重新编译
使用 re.compile()函数,我们可以将模式编译成模式对象,
,它有各种操作的方法,比如搜索模式匹配
或执行字符串替换。
让我们看两个例子,使用 re.compile()函数。
第一个例子检查用户的输入是否只包含字母、
空格或。(无数字)
不允许使用任何其他字符。
`import re
name_check = re.compile(r"[^A-Za-zs.]")
name = raw_input ("Please, enter your name: ")
while name_check.search(name):
print "Please enter your name correctly!"
name = raw_input ("Please, enter your name: ")`
第二个例子检查用户的输入是否只包含数字、
括号、空格或连字符(没有字母)
不允许使用任何其他字符
`import re
phone_check = re.compile(r"[^0-9s-()]")
phone = raw_input ("Please, enter your phone: ")
while phone_check.search(phone):
print "Please enter your phone correctly!"
phone = raw_input ("Please, enter your phone: ")`
上述脚本的输出将是:
请输入您的电话号码
请正确输入您的电话号码!
它将继续询问,直到你只输入数字。
在地址中查找电子邮件域
让我们用我在 stackoverflow 上找到的一个简洁的脚本来结束这篇关于 Python 中正则表达式的文章。
@
扫描直到看到这个字符
【w .】
潜在匹配的一组字符,所以 w 是全字母数字字符,
和尾随句点。添加到该字符集。
****++
先前设定的一个或多个。
因为这个正则表达式匹配句点字符和@后面的每一个字母数字
,所以它甚至会匹配句子中间的电子邮件域。
`import re
s = 'My name is Conrad, and [[email protected]](/cdn-cgi/l/email-protection) is my email.'
domain = re.search("@[w.]+", s)
print domain.group()`
输出:
@gmail.com
更多阅读
https://developers . Google . com/edu/python/regular-expressions
http://www.doughellmann.com/PyMOTW/re/
http://www.daniweb.com/
在 Python 中从字符串中移除字符
原文:https://www.pythonforbeginners.com/basics/remove-a-character-from-a-string-in-python
我们在 Python 中使用字符串来操作文本数据。在分析文本数据时,我们可能需要从数据中删除一些字符。在本文中,我们将讨论在 Python 中从字符串中删除字符的不同方法。
在 Python 中使用 For 循环从字符串中删除字符
我们使用 for 循环来遍历 iterable 对象的元素。我们将使用以下方法,通过 Python 中的 for 循环从字符串中删除一个字符。
- 首先,我们将定义一个名为
newStr的空字符串来存储输出字符串。 - 现在,我们将使用 for 循环遍历输入字符串的字符。
- 在迭代过程中,如果我们发现一个字符不等于我们想要删除的字符,我们将把这个字符附加到
newStr。 - 如果我们找到需要删除的字符,我们跳过它。
在执行 for 循环之后,我们将在变量newStr中获得输出字符串。您可以在下面的示例中观察到这一点。
input_string = "Adcictcya"
char_to_remove = "c"
newStr = ""
for character in input_string:
if character != char_to_remove:
newStr += character
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
在这里,您可以看到我们已经从输入字符串'Adcictcya'中删除了字符'c',以生成输出字符串'Aditya'。
在 Python 中使用列表理解从字符串中移除字符
在 Python 中,我们可以使用 list comprehension 从输入字符串中删除一个字符,而不是使用 for 循环。为此,我们将使用以下方法。
- 首先,我们将使用 list comprehension 来创建一个输入字符串的字符列表,在此之前,我们将删除想要删除的字符。我们将把列表存储在变量
myList中。 - 在创建了
myList之后,我们将定义一个名为newStr的空字符串来存储输出字符串。 - 现在,我们将使用 for 循环遍历列表中的元素。
- 在迭代过程中,我们将使用字符串连接来连接
myList到newStr的每个元素。 - 在执行 for 循环后,我们将在变量
newStr中获得所需的输出字符串。您可以在下面的示例中观察到这一点。
input_string = "Adcictcya"
char_to_remove = "c"
myList = [character for character in input_string if character != char_to_remove]
newStr = ""
for character in myList:
newStr += character
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
创建myList后,我们可以使用join()方法代替 for 循环来创建输出字符串。
当在分隔符字符串上调用时,join()方法将 iterable 对象作为其输入参数。执行后,它返回一个字符串,其中 iterable 对象的所有元素都由分隔符分隔。
我们将使用下面的方法,使用 list comprehension 和 join()方法从 python 中的字符串中删除一个字符。
- 首先,我们将使用 list comprehension 来创建一个输入字符串的字符列表,在此之前,我们将删除想要删除的字符。我们将把列表存储在变量
myList中。 - 现在,我们将定义一个空字符串作为分隔符。
- 定义分隔符后,我们将调用分隔符上的
join()方法。这里,我们将把myList作为输入参数传递给join()方法。 - 执行后,
join()方法将返回所需的字符串。
您可以在下面的示例中观察到这一点。
input_string = "Adcictcya"
char_to_remove = "c"
myList = [character for character in input_string if character != char_to_remove]
separator = ""
newStr = separator.join(myList)
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
在 Python 中使用 split()方法从字符串中移除字符
方法split()用于将一个字符串分割成子字符串。当在字符串上调用时,它将一个字符作为其输入参数。执行后,它返回在给定字符处拆分的原始字符串的子字符串列表。
要使用split()方法从 Python 中的字符串中删除一个字符,我们将使用以下步骤。
- 首先,我们将对输入字符串调用
split()方法。这里,我们将需要从字符串中删除的字符作为输入参数进行传递。 - 执行后,
split()方法将返回一个列表。我们将列表存储在myList中。 - 现在,我们将定义一个名为
newStr的空字符串来存储输出字符串。 - 之后,我们将使用 for 循环遍历列表中的元素。
- 在迭代过程中,我们将使用字符串连接来连接
myList到newStr的每个元素。
在执行 for 循环后,我们将在变量myStr中获得所需的输出字符串。您可以在下面的示例中观察到这一点。
input_string = "Adcictcya"
char_to_remove = "c"
myList = input_string.split(char_to_remove)
newStr = ""
for element in myList:
newStr += element
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
不使用 for 循环和字符串连接来创建来自myList的输出字符串,我们可以使用如下的join()方法。
- 首先,我们将对输入字符串调用
split()方法。这里,我们将需要从字符串中删除的字符作为输入参数进行传递。 - 执行后,
split()方法将返回一个列表。我们将列表存储在myList中。 - 现在,我们将定义一个空字符串作为分隔符。
- 定义分隔符后,我们将调用分隔符上的
join()方法。这里,我们将把myList作为输入参数传递给join()方法。 - 执行后,
join()方法将返回输出字符串。
您可以在下面的示例中观察整个过程。
input_string = "Adcictcya"
char_to_remove = "c"
myList = input_string.split(char_to_remove)
separator = ""
newStr = separator.join(myList)
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
在 Python 中使用 filter()函数从字符串中移除字符
filter()函数用于根据条件过滤可迭代对象的元素。filter() 函数将另一个函数作为它的第一个输入参数,将一个 iterable 对象作为它的第二个输入参数。作为第一个输入参数给出的函数必须将 iterable 对象的元素作为其输入,并为每个元素返回 True 或 False。
执行后,filter() 函数返回一个迭代器,其中包含输入参数中给定的 iterable 对象的所有元素,对于这些元素,第一个输入参数中给定的函数返回 True。
要使用 filter 函数从给定的字符串中删除一个字符,我们将使用以下步骤。
- 首先,我们将定义一个函数
myFun,它把给定字符串的字符作为它的输入参数。如果输入参数中给出的字符是需要删除的字符,则返回 False。否则,它返回 True。 - 在定义了
myFun之后,我们将把myFun和输入字符串分别作为第一和第二输入参数传递给filter()函数。 - 执行后,filter 函数返回一个包含字符串字符的迭代器。我们将使用
list()函数将迭代器转换成一个列表。我们将列表存储在myList中。 - 现在,我们将定义一个名为
newStr的空字符串来存储输出字符串。 - 之后,我们将使用 for 循环遍历列表中的元素。
- 在迭代过程中,我们将使用字符串连接来连接
myList到newStr的每个元素。
在执行 for 循环后,我们将在变量newStr中获得所需的输出字符串。您可以在下面的示例中观察到这一点。
def myFun(character):
char_to_remove = "c"
return character != char_to_remove
input_string = "Adcictcya"
char_to_remove = "c"
filter_object = filter(myFun, input_string)
myList = list(filter_object)
newStr = ""
for element in myList:
newStr += element
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
您还可以使用 join()方法通过以下步骤创建输出字符串。
- 首先,我们将定义一个函数 myFun,它将给定字符串的字符作为输入参数。如果输入参数中给出的字符是需要删除的字符,则返回 False。否则,它返回 True。
- 在定义了
myFun之后,我们将把myFun和输入字符串分别作为第一和第二输入参数传递给filter()函数。 - 执行后,filter 函数返回一个包含字符串字符的迭代器。我们将使用
list()函数将迭代器转换成一个列表。我们将列表存储在myList中。 - 现在,我们将定义一个空字符串作为分隔符。
- 定义分隔符后,我们将调用分隔符上的
join()方法。这里,我们将把myList作为输入参数传递给join()方法。 - 执行后,
join()方法将返回输出字符串。
您可以在下面的示例中观察整个过程。
def myFun(character):
char_to_remove = "c"
return character != char_to_remove
input_string = "Adcictcya"
char_to_remove = "c"
filter_object = filter(myFun, input_string)
myList = list(filter_object)
separator = ""
newStr = separator.join(myList)
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
不使用myFun,你可以使用一个λ表达式和filter()函数,如下所示。
input_string = "Adcictcya"
char_to_remove = "c"
filter_object = filter(lambda character:character!=char_to_remove, input_string)
myList = list(filter_object)
separator = ""
newStr = separator.join(myList)
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
这里,lambda 表达式执行与前面代码中的myFun相同的任务。
在 Python 中使用 replace()方法从字符串中移除字符
replace()方法用于将字符串中的一个字符替换为另一个字符。您也可以使用 replace()方法从字符串中删除一个字符。在字符串上调用时,replace()方法将需要替换的字符作为第一个参数,新字符作为第二个输入参数。执行后,它返回修改后的字符串。
为了使用replace() 方法从字符串中删除一个字符,我们将对原始字符串调用replace() 方法。这里,将需要删除的字符作为第一个输入参数,一个空字符串作为第二个输入参数传递给replace()方法。
执行后, replace() 方法将返回输出字符串。您可以在下面的示例中观察到这一点。
input_string = "Adcictcya"
char_to_remove = "c"
newStr = input_string.replace(char_to_remove, "")
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
在 Python 中使用 translate()方法从字符串中移除字符
translate()方法也用于替换字符串中的字符。当在字符串上调用时,translate()方法将一个翻译表作为它的输入参数。执行后,它返回修改后的字符串。
要从给定的字符串中删除一个字符,我们首先要做一个翻译表。为此,我们可以使用maketrans()方法。
在字符串上调用maketrans()方法时,将一个字符串作为第一个参数,另一个包含相同数量字符的字符串作为第二个输入参数中的第一个参数。执行后,它返回一个转换表。
- 为了制作从给定字符串中删除字符的转换表,我们将需要删除的字符作为第一个输入参数,一个空格字符作为第二个输入参数传递给
maketrans()方法。执行后,maketrans()方法将返回一个转换表,将需要删除的字符映射到一个空白字符。 - 现在,我们将调用输入字符串上的
translate()方法,将翻译表作为其输入参数。在执行了translate()方法之后,我们将得到一个字符串,其中需要删除的字符被一个空白字符替换。 - 接下来,我们将使用
split()方法将translate()方法返回的字符串拆分成一个列表。我们将把列表存储在一个名为myList的变量中。 - 接下来,我们将定义一个名为
newStr的空字符串来存储输出字符串。 - 之后,我们将使用 for 循环遍历列表中的元素。
- 在迭代过程中,我们将使用字符串连接来连接
myList到newStr的每个元素。
在执行 for 循环后,我们将在变量newStr中获得所需的输出字符串。您可以在下面的示例中观察到这一点。
input_string = "Adcictcya"
char_to_remove = "c"
translation_table = input_string.maketrans(char_to_remove, " ")
tempStr = input_string.translate(translation_table)
myList = tempStr.split()
newStr = ""
for element in myList:
newStr += element
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
您可以使用 join()方法从myList创建输出字符串,而不是使用 for 循环和字符串串联。为此,您可以使用以下步骤。
- 首先,将定义一个空字符串作为分隔符。
- 定义分隔符后,我们将调用分隔符上的
join()方法。这里,我们将把myList作为输入参数传递给join()方法。 - 执行后,
join()方法将返回输出字符串。
您可以在下面的示例中观察整个过程。
input_string = "Adcictcya"
char_to_remove = "c"
translation_table = input_string.maketrans(char_to_remove, " ")
tempStr = input_string.translate(translation_table)
myList = tempStr.split()
separator=""
newStr = separator.join(myList)
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
使用translate()方法的方法只适用于不包含空白字符的字符串。因此,如果输入字符串中有空白字符,就不能使用这种方法。
在 Python 中使用正则表达式从字符串中移除字符
正则表达式为我们提供了 Python 中字符串操作的各种函数。在 Python 中,还可以使用正则表达式从字符串中移除字符。为此,我们将使用sub() 函数。
sub()函数用于替换字符串中的字符。它需要三个输入参数。第一个输入参数是需要替换的字符。第二个参数是替换字符。最后,第三个输入参数是原始字符串。执行后,sub()函数返回新的字符串。
要使用sub()函数从字符串中删除一个字符,我们将使用以下步骤。
- 在
sub()函数的第一个参数中,我们将传递需要删除的字符。 - 我们将把一个空字符串作为第二个输入参数,把原始字符串作为第三个输入参数传递给
sub()函数。 - 在执行了
sub()函数之后,我们将得到想要的输出字符串。
您可以在下面的示例中观察到这一点。
import re
input_string = "Adcictcya"
char_to_remove = "c"
newStr = re.sub(char_to_remove, "", input_string)
print("The input string is:", input_string)
print("The character to delete is:", char_to_remove)
print("The output string is:", newStr)
输出:
The input string is: Adcictcya
The character to delete is: c
The output string is: Aditya
结论
在本文中,我们讨论了在 Python 中从字符串中删除字符的不同方法。在所有这些方法中,使用re.sub()函数和 replace()方法的方法是最有效的。因此,在 Python 中,应该使用这两种方法从字符串中删除字符。
要了解更多关于 python 编程的知识,您可以阅读这篇关于如何在 Python 中从列表或字符串中删除所有出现的字符的文章。你可能也会喜欢这篇关于机器学习中回归的文章。你也可以看看这篇关于数据分析师 vs 数据科学家的文章。
请继续关注更多内容丰富的文章。快乐学习!
在 Python 中移除列表或字符串中出现的所有字符
在自然语言处理、数据科学和数据挖掘等领域,我们需要处理大量的文本数据。为此,我们通常在 Python 中使用字符串和列表。给定一个字符列表或字符串,我们有时需要从列表或字符串中删除一个或所有出现的字符。在本文中,我们将讨论在 python 中从列表或字符串中删除所有出现的字符的不同方法。
使用 pop()方法从列表中移除元素
给定一个列表,我们可以使用pop()方法从列表中删除一个元素。当在列表上调用pop() 方法时,从列表中删除最后一个元素。执行后,它返回删除的元素。您可以在下面的示例中观察到这一点。
myList = [1, 2, 3, 4, 5, 6, 7]
print("The original list is:", myList)
x = myList.pop()
print("The popped element is:", x)
print("The modified list is:", myList)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7]
The popped element is: 7
The modified list is: [1, 2, 3, 4, 5, 6]
在上面的例子中,您可以看到在执行了pop()方法之后,列表的最后一个元素已经从列表中删除了。
但是,如果输入列表为空,程序将运行到IndexError。这意味着你试图从一个空列表中弹出一个元素。例如,看看下面的例子。
myList = []
print("The original list is:", myList)
x = myList.pop()
print("The popped element is:", x)
print("The modified list is:", myList)
输出:
The original list is: []
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
x = myList.pop()
IndexError: pop from empty list
您可以观察到程序遇到了一个IndexError异常,并显示消息“IndexError: pop from empty list”。
您还可以使用pop()方法从列表中的特定索引中删除元素。为此,您需要提供元素的索引。
当在列表上调用时,pop()方法将需要删除的元素的索引作为其输入参数。执行后,它从给定的索引中移除元素。pop()方法也返回被移除的元素。您可以在下面的示例中观察到这一点。
myList = [1, 2, 3, 4, 5, 6, 7, 8]
print("The original list is:", myList)
x = myList.pop(3)
print("The popped element is:", x)
print("The modified list is:", myList)
输出:
The original list is: [1, 2, 3, 4, 5, 6, 7, 8]
The popped element is: 4
The modified list is: [1, 2, 3, 5, 6, 7, 8]
这里,我们使用pop()方法弹出了列表中索引 3 处的元素。
使用 remove()方法从列表中删除元素
如果不知道要删除的元素的索引,可以使用 remove() 方法。当在列表上调用时,remove()方法将一个元素作为它的输入参数。执行后,它从列表中移除第一个出现的 input 元素。remove() 方法不返回任何值。换句话说,它返回None。
您可以在下面的示例中观察到这一点。
myList = [1, 2, 3, 4,3, 5,3, 6, 7, 8]
print("The original list is:", myList)
myList.remove(3)
print("The modified list is:", myList)
输出:
The original list is: [1, 2, 3, 4, 3, 5, 3, 6, 7, 8]
The modified list is: [1, 2, 4, 3, 5, 3, 6, 7, 8]
在上面的例子中,您可以看到在执行了remove()方法之后,第一次出现的元素 3 被从列表中删除。
如果remove()方法的输入参数中给出的值不在列表中,程序将运行到如下所示的ValueError异常。
myList = []
print("The original list is:", myList)
myList.remove(3)
print("The modified list is:", myList)
输出:
The original list is: []
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myList.remove(3)
ValueError: list.remove(x): x not in list
在上面的例子中,列表是空的。因此,数字 3 不是列表中的一个元素。因此,当我们调用remove()方法时,程序运行到ValueError异常,并显示消息“ValueError: list.remove(x): x not in list”。
到目前为止,我们已经讨论了如何从列表中删除一个元素。现在让我们来讨论如何在 python 中删除字符列表中某个字符的所有出现。
从列表中删除所有出现的字符
给定一个字符列表,我们可以使用 for 循环和append()方法删除所有出现的值。为此,我们将使用以下步骤。
- 首先,我们将创建一个名为
outputList的空列表。为此,您可以使用方括号或list()构造函数。 - 创建完
outputList后,我们将使用 for 循环遍历输入的字符列表。 - 在遍历列表元素时,我们将检查是否需要删除当前字符。
- 如果是,我们将使用继续语句移动到下一个字符。否则,我们将使用
append()方法将当前字符追加到outputList中。
在执行 for 循环之后,我们将在 output list 中获得字符的输出列表。在 outputList 中,除了那些我们需要从原始列表中删除的字符之外,所有的字符都将出现。您可以在下面的 python 程序中观察到这一点。
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
outputList = []
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
for character in myList:
if character == charToDelete:
continue
outputList.append(character)
print("The modified list is:", outputList)
输出:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
使用列表理解从列表中删除一个字符的所有出现
不使用 for 循环,我们可以使用列表理解和成员操作符“in”来删除给定字符的所有出现。
in操作符是一个二元操作符,它将一个元素作为第一个操作数,将一个容器对象(如 list)作为第二个操作数。执行后,如果容器对象中存在该元素,它将返回True。否则,它返回False。您可以在下面的示例中观察到这一点。
myList = [1, 2, 3, 4,3, 5,3, 6, 7, 8]
print("The list is:", myList)
print(3 in myList)
print(1117 in myList)
输出:
The list is: [1, 2, 3, 4, 3, 5, 3, 6, 7, 8]
True
False
使用 list comprehension 和'in'操作符,我们可以创建一个新列表,其中包含除了我们需要从原始列表中删除的字符之外的所有字符,如下例所示。
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList = [character for character in myList if character != charToDelete]
print("The modified list is:", outputList)
输出:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
使用 Remove()方法从列表中移除元素的所有匹配项
我们也可以从原来的列表中删除一个角色的所有实例,而不是创建一个新的列表。为此,我们将使用remove()方法和成员操作符“in”。
- 为了从给定的字符列表中删除给定元素的所有实例,我们将使用'
in'操作符检查该字符是否出现在列表中。如果是,我们将使用 remove 方法从列表中删除该字符。 - 我们将使用一个 while 循环来反复检查该字符的存在,以将其从列表中删除。
- 在删除给定字符的所有匹配项后,程序将从 while 循环中退出。
这样,我们将通过修改原始列表得到输出列表,如下所示。
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
while charToDelete in myList:
myList.remove(charToDelete)
print("The modified list is:", myList)
输出:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
使用 filter()函数删除所有出现的字符
我们也可以使用filter()函数从字符列表中删除所有出现的字符。
filter()函数将另一个函数比如myFun作为它的第一个输入参数,将一个类似 list 的容器对象作为它的第二个参数。这里,myFun应该把容器对象的一个元素作为它的输入参数。执行后,它应该返回True或False。
如果对于输入中给定的容器对象的任何元素,myFun的输出是True,则该元素包含在输出中。否则,元素不会包含在输出中。
要使用filter()方法删除列表中给定项目的所有出现,我们将遵循以下步骤。
- 首先,我们将定义一个函数
myFun,它将一个字符作为输入参数。如果输入的字符等于我们需要删除的字符,它返回False。否则,它应该返回True。 - 定义了
myFun之后,我们将把myFun作为第一个参数,把字符列表作为第二个输入参数传递给filter()函数。 - 执行后,
filter()函数将返回一个 iterable 对象,其中包含没有从列表中删除的字符。 - 为了将 iterable 对象转换成列表,我们将把 iterable 对象传递给
list()构造函数。这样,我们将在删除所有出现的指定字符后得到列表。
您可以在下面的示例中观察整个过程。
def myFun(character):
charToDelete = 'c'
return charToDelete != character
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList=list(filter(myFun,myList))
print("The modified list is:", outputList)
输出:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
不用定义函数myFun,我们可以创建一个 lambda 函数,并将其传递给过滤函数,以从列表中删除所有的字符实例。你可以这样做。
myList = ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r',
's']
print("The original list is:", myList)
charToDelete = 'c'
print("The character to be removed is:", charToDelete)
outputList = list(filter(lambda character: character != charToDelete, myList))
print("The modified list is:", outputList)
输出:
The original list is: ['p', 'y', 'c', 't', 'c', 'h', 'o', 'n', 'f', 'c', 'o', 'r', 'b', 'e', 'g', 'c', 'i', 'n', 'n', 'c', 'e', 'r', 's']
The character to be removed is: c
The modified list is: ['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
到目前为止,我们已经讨论了不同的方法来删除列表中出现的所有字符。现在我们将讨论如何从 python 字符串中删除特定字符的出现。
在 Python 中移除字符串中出现的所有字符
给定一个输入字符串,我们可以使用不同的字符串方法和正则表达式方法从字符串中删除一个或所有出现的字符。让我们逐一讨论它们。
在 Python 中使用 for 循环删除字符串中出现的所有字符
要使用 for 循环从字符串中删除所有出现的特定字符,我们将遵循以下步骤。
- 首先,我们将创建一个名为
outputString的空字符串来存储输出字符串。 - 之后,我们将遍历原始字符串的字符。
- 在迭代字符串的字符时,如果我们找到了需要从字符串中删除的字符,我们将使用 continue 语句移动到下一个字符。
- 否则,我们将把当前字符连接到
outputString。
在使用上述步骤的 for 循环迭代到字符串的最后一个字符之后,我们将在名为outputString的新字符串中获得输出字符串。您可以在下面的代码示例中观察到这一点。
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = ""
for character in myStr:
if character == charToDelete:
continue
outputString += character
print("The modified string is:", outputString)
输出:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
使用列表理解从 Python 中的字符串中移除所有出现的字符
不使用 for 循环,我们可以使用 list comprehension 和 join()方法从给定的字符串中删除特定值的出现。
- 首先,我们将使用 list comprehension 为字符串创建一个不需要删除的字符列表,如下所示。
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = [character for character in myStr if character != charToDelete]
print("The list of characters is:")
print(myList)
输出:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list of characters is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
- 获得列表后,我们将使用
join()方法创建输出列表。当对特殊字符调用join()方法时,该方法将包含字符或字符串的 iterable 对象作为其输入参数。执行后,它返回一个字符串。输出字符串包含输入 iterable 对象的字符,由调用 join 方法的特殊字符分隔。 - 我们将使用空字符
“”作为特殊字符。我们将调用空字符上的join()方法,将上一步获得的列表作为它的输入参数。在执行了join()方法之后,我们将得到想要的输出字符串。您可以在下面的示例中观察到这一点。
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = [character for character in myStr if character != charToDelete]
print("The list of characters is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
输出:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list of characters is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
在 Python 中使用 split()方法删除字符串中出现的所有字符
我们还可以使用split()方法从给定的字符串中删除一个字符的所有出现。在字符串上调用split()方法时,它将分隔符作为输入参数。执行后,它返回由分隔符分隔的子字符串列表。
要从给定的字符串中删除给定字符的所有出现,我们将使用以下步骤。
- 首先,我们将在原始字符串上调用
split()方法。w 将把需要删除的字符作为输入参数传递给split()方法。我们将把split()方法的输出存储在myList中。 - 获得
myList后,我们将调用空字符串上的join()方法,并将myList作为join()方法的输入参数。 - 在执行了
join()方法之后,我们将得到想要的输出。所以,我们将它存储在一个变量outputString中。
您可以在下面的示例中观察整个过程。
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = myStr.split(charToDelete)
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
输出:
The character to delete: c
The list is:
['py', 't', 'honf', 'orbeg', 'inn', 'ers']
The modified string is: pythonforbeginners
在 Python 中,使用 filter()函数移除字符串中出现的所有字符
在 Python 中,我们还可以将 filter() 函数与join()方法和 lambda 函数结合使用,来删除字符串中出现的字符。
filter()函数将另一个函数比如说myFun作为它的第一个输入参数,将一个类似 string 的可迭代对象作为它的第二个输入参数。这里,myFun应该把字符串对象的字符作为它的输入参数。执行后,它应该返回True或False。
如果对于输入中给定的字符串对象的任何字符,myFun的输出为True,则该字符包含在输出中。否则,字符不会包含在输出中。
要删除字符串中给定字符的所有出现,我们将遵循以下步骤。
- 首先,我们将定义一个函数
myFun,它将一个字符作为输入参数。如果输入字符等于必须删除的字符,它返回False。否则,它应该返回True。 - 定义了
myFun之后,我们将把myFun作为第一个参数,把字符串作为第二个输入参数传递给filter()函数。 - 执行后,
filter()函数将返回一个 iterable 对象,其中包含没有从字符串中删除的字符。 - 我们将通过将 iterable 对象传递给
list()构造函数来创建一个字符列表。 - 一旦我们得到了字符列表,我们将创建输出字符串。为此,我们将调用空字符串上的
join()方法,将字符列表作为其输入参数。 - 在执行了
join()方法之后,我们将得到想要的字符串。
您可以在下面的代码中观察整个过程。
def myFun(character):
charToDelete = 'c'
return charToDelete != character
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = list(filter(myFun, myStr))
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
输出:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
不用定义函数myFun,我们可以创建一个等价的 lambda 函数,并将它传递给 filter 函数,从字符串中删除该字符的所有实例。你可以这样做。
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
myList = list(filter(lambda character: character != charToDelete, myStr))
print("The list is:")
print(myList)
outputString = "".join(myList)
print("The modified string is:", outputString)
输出:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The list is:
['p', 'y', 't', 'h', 'o', 'n', 'f', 'o', 'r', 'b', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
The modified string is: pythonforbeginners
在 Python 中使用 replace()方法删除字符串中出现的所有字符
在字符串上调用replace()方法时,将需要替换的字符作为第一个参数。在第二个参数中,它用将要替换的字符代替第一个参数中给出的原始字符。
执行后,replace()方法返回作为输入给出的字符串的副本。在输出字符串中,所有字符都被替换为新字符。
为了从字符串中删除一个给定字符的所有出现,我们将对字符串调用replace()方法。我们将传递需要删除的字符作为第一个输入参数。在第二个输入参数中,我们将传递一个空字符串。
执行后,所有出现的字符将被替换为空字符串。因此,我们可以说这个字符已经从字符串中删除了。
您可以在下面的示例中观察整个过程。
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = myStr.replace(charToDelete, "")
print("The modified string is:", outputString)
输出:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
在 Python 中,使用 translate()方法移除字符串中出现的所有字符
我们也可以使用 translate()方法从字符串中删除字符。当在字符串上调用translate()方法时,它将一个翻译表作为输入参数。执行后,它根据转换表返回修改后的字符串。
可以使用maketrans()方法创建转换表。在字符串上调用maketrans()方法时,将需要替换的字符作为第一个参数,新字符作为第二个参数。执行后,它返回一个转换表。
我们将使用以下步骤从字符串中删除给定的字符。
- 首先,我们将对输入字符串调用
maketrans()方法。我们将需要删除的字符作为第一个输入参数,一个空格字符作为第二个输入参数传递给maketrans()方法。这里,我们不能将空字符传递给maketrans()方法,这样它就可以将字符映射到空字符串。这是因为两个字符串参数的长度应该相同。否则,maketrans()方法会出错。 - 执行后,
maketrans()方法将返回一个转换表,将我们需要删除的字符映射到一个空格字符。 - 一旦我们得到了翻译表,我们将调用输入字符串上的
translate()方法,将翻译表作为它的输入参数。 - 执行后,
translate()方法将返回一个字符串,其中我们需要删除的字符被替换为空格字符。 - 为了从字符串中删除空格字符,我们将首先在
translate()方法的输出上调用split()方法。在这一步之后,我们将得到一个子字符串列表。 - 现在,我们将在一个空字符串上调用
join()方法。这里,我们将把子字符串列表作为输入传递给join()方法。 - 在执行了
join()方法之后,我们将得到想要的字符串。
您可以在下面的代码中观察整个过程。
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
translationTable = myStr.maketrans(charToDelete, " ")
outputString = "".join(myStr.translate(translationTable).split())
print("The modified string is:", outputString)
输出:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
在 Python 中使用正则表达式删除字符串中出现的所有字符
正则表达式提供了一种最有效的操作字符串或文本数据的方法。
要从字符串中删除一个字符,我们可以使用在re模块中定义的sub()方法。 sub()方法将需要替换的字符比如说old_char作为它的第一个输入参数。它将新字符new_char作为第二个输入参数,输入字符串作为第三个参数。执行后,它将输入字符串中的old_char替换为new_char,并返回一个新的字符串。
要从给定的字符串中删除一个字符的所有出现,我们将使用以下步骤。
- 我们将需要删除的字符作为第一个输入参数
old_char传递给sub()方法。 - 作为第二个参数
new_char,我们将传递一个空字符串。 - 我们将输入字符串作为第三个参数传递给
sub()方法。
执行后,sub() 方法将返回一个新的字符串。在新字符串中,需要删除的字符将被空字符串字符替换。因此,我们将得到期望的输出字符串。
您可以在下面的代码中观察到这一点。
import re
myStr = "pyctchonfcorbegcinncers"
print("The original string is:", myStr)
charToDelete = 'c'
print("The character to delete:", charToDelete)
outputString = re.sub(charToDelete, "", myStr)
print("The modified string is:", outputString)
输出:
The original string is: pyctchonfcorbegcinncers
The character to delete: c
The modified string is: pythonforbeginners
结论
在本文中,我们讨论了从列表中删除一个字符的所有匹配项的不同方法。同样,我们已经讨论了不同的方法来删除字符串中出现的所有字符。对于列表,我建议您使用带有remove()方法的方法。对于字符串,您可以使用replace()方法或re.sub()方法,因为这是删除列表中的所有字符或 python 中的字符串的最有效方法
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中删除字符串中的逗号
原文:https://www.pythonforbeginners.com/strings/remove-commas-from-string-in-python
在 python 中,我们使用字符串来分析文本数据。在分析之前,我们需要对文本数据进行预处理。有时,我们可能需要从文本中删除像逗号或撇号这样的字符。在本文中,我们将讨论如何在 python 中删除给定字符串中的逗号。
使用 for 循环删除字符串中的逗号
从字符串中删除逗号最简单的方法是创建一个新的字符串,留下逗号。
在这种方法中,我们将首先创建一个空字符串newString。之后,我们将使用 for 循环逐个字符地遍历输入字符串。在遍历时,我们将检查当前字符是否是逗号。如果字符不是逗号,我们将使用字符串连接操作将当前字符添加到newString中。一旦 for 循环的执行完成,我们将得到变量newString中没有逗号的输出字符串。
您可以在下面的示例中观察整个过程。
myString = "This, is, a, string, that, has, commas, in, it."
print("Original String:", myString)
newString = ""
for character in myString:
if character != ",":
newString = newString + character
print("Output String:", newString)
输出:
Original String: This, is, a, string, that, has, commas, in, it.
Output String: This is a string that has commas in it.
使用 replace()方法
我们可以使用replace()方法从任何给定的字符串中删除逗号,而不是遍历整个字符串来删除字符串中的逗号。
replace 方法的语法如下。
str.replace(old_character, new_character, count)
这里,
- 参数
old_character用于将需要删除的字符传递给 replace 方法。我们将删除逗号“,”作为第一个输入参数。 - 参数
new_character用于传递将替换old_character的字符。我们将传递一个空字符串作为new_character,以便删除逗号字符。 - 参数 count 用于决定字符串中有多少个
old_character实例将被new_character替换。这是一个可选参数,我们可以让它为空。在这种情况下,字符串中所有的old_character实例都将被替换为new_character。 - 在用
new_character替换了old_character的所有实例之后,replace()方法返回修改后的字符串。
我们可以使用str.replace()方法从给定的字符串中删除逗号,如下所示。
myString = "This, is, a, string, that, has, commas, in, it."
print("Original String:", myString)
newString = myString.replace(",", "")
print("Output String:", newString)
输出:
Original String: This, is, a, string, that, has, commas, in, it.
Output String: This is a string that has commas in it.
使用 re.sub()方法删除字符串中的逗号
正则表达式是操作字符串的一个很好的工具。在 python 中,我们也可以用它们来删除字符串中的逗号。为此,我们将使用re.sub()方法。
re.sub()方法的语法如下。
re.sub(old_character, new_character, input_string)
这里,
-
参数
old_character用于将需要移除的字符传递给re.sub()方法。我们将删除逗号“,”作为第一个输入参数。 -
参数
new_character用于传递将替换old_character的字符。我们将传递一个空字符串作为new_character,以便删除逗号字符。 -
input_string参数用于将需要修改的字符串传递给re.sub()方法。 -
执行后,该方法返回修改后的字符串。
我们可以使用re.sub()方法从给定的字符串中删除逗号,如下所示。
import re
myString = "This, is, a, string, that, has, commas, in, it."
print("Original String:", myString)
newString = re.sub(",", "", myString)
print("Output String:", newString)
输出:
Original String: This, is, a, string, that, has, commas, in, it.
Output String: This is a string that has commas in it.
结论
在本文中,我们讨论了在 python 中删除字符串中逗号的三种方法。要了解更多关于 python 中的字符串,可以阅读这篇关于 python 中的正则表达式的文章。你可能也会喜欢这篇关于用 python 理解列表的文章。
在 Python 中从集合中移除元素
原文:https://www.pythonforbeginners.com/basics/remove-elements-from-a-set-in-python
我们在 python 中使用集合来存储唯一的不可变对象。在本文中,我们将讨论如何在 python 中从集合中移除元素。为此,我们将讨论使用不同方法的四种途径。
使用 pop()方法从集合中移除元素
我们可以使用 pop()方法从集合中移除元素。当在集合上调用时,pop()方法不接受输入参数。执行后,它从集合中移除一个随机元素,并返回该元素。您可以在下面的示例中观察到这一点。
mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
element = mySet.pop()
print("The output set is:", mySet)
print("The popped element is:", element)
输出:
The input set is: {1, 2, 3, 4, 5, 6}
The output set is: {2, 3, 4, 5, 6}
The popped element is: 1
pop()方法只适用于非空集合。如果我们在空集上调用pop()方法,它将引发KeyError异常,如下所示。
mySet = set()
print("The input set is:", mySet)
element = mySet.pop()
print("The output set is:", mySet)
print("The popped element is:", element)
输出:
The input set is: set()
/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 3, in <module>
element = mySet.pop()
KeyError: 'pop from an empty set'
方法从集合中删除一个随机元素。如果我们必须删除一个特定的元素,我们可以使用下面讨论的方法。
使用 Remove()方法从集合中移除元素
要从集合中删除指定的元素,我们可以使用remove() 方法。在集合上调用 remove()方法时,该方法将一个元素作为输入参数,并从集合中删除该元素,如下所示。
mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.remove(3)
print("The output set is:", mySet)
输出:
The input set is: {1, 2, 3, 4, 5, 6}
The output set is: {1, 2, 4, 5, 6}
如果作为输入传递给remove()方法的元素不在集合中,程序将运行到一个KeyError异常,如下所示。
mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.remove(7)
print("The output set is:", mySet)
输出:
The input set is: {1, 2, 3, 4, 5, 6}
/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 3, in <module>
mySet.remove(7)
KeyError: 7
类似地,如果我们试图使用remove()方法从空集合中移除一个元素,它将引发KeyError异常。
mySet = set()
print("The input set is:", mySet)
mySet.remove(7)
print("The output set is:", mySet)
输出:
The input set is: set()
/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 3, in <module>
mySet.remove(7)
KeyError: 7
使用 discard()方法从集合中移除元素
当我们试图使用remove()方法从集合中删除一个元素,而该元素不在集合中时,程序将运行到一个KeyError异常。您可以使用discard() 方法而不是remove()方法来避免这种情况。当在集合上调用discard()方法时,该方法接受一个元素作为输入参数,并从集合中删除该元素,就像在remove()方法中一样。
mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.discard(3)
print("The output set is:", mySet)
输出:
The input set is: {1, 2, 3, 4, 5, 6}
The output set is: {1, 2, 4, 5, 6}
然而,如果我们尝试用删除集合中不存在的元素,discard()方法不会引发异常。该设置保持不变,程序不会遇到KeyError异常。
mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.discard(7)
print("The output set is:", mySet)
输出:
The input set is: {1, 2, 3, 4, 5, 6}
The output set is: {1, 2, 3, 4, 5, 6}
使用 clear()方法
clear() 方法用于一次从任何给定的集合中删除所有元素。当在集合上调用时,clear()方法不接受输入参数,并从集合中删除所有元素。您可以在下面的示例中观察到这一点。
mySet = {1, 2, 3, 4, 5, 6}
print("The input set is:", mySet)
mySet.clear()
print("The output set is:", mySet)
输出:
The input set is: {1, 2, 3, 4, 5, 6}
The output set is: set()
结论
在本文中,我们讨论了在 python 中从集合中删除元素的四种方法。要了解更多关于集合的知识,你可以阅读这篇关于 Python 中集合理解的文章。你可能也会喜欢这篇关于用 Python 阅读列表的文章。
在 Python 中删除字符串中的引号
原文:https://www.pythonforbeginners.com/basics/remove-quotes-from-a-string-in-python
由于各种模块的可用性,Python 是自然语言处理和文本分析中最常用的编程语言之一。我们使用 python 中的字符串来分析文本数据。在 Python 中,单引号或双引号将每个字符串括起来。但是,输入字符串之间可能包含引号。本文讨论了在 Python 中从字符串中移除引号的不同方法。
在 Python 中使用 For 循环删除字符串中的引号
在 Python 中,我们使用 for 循环来迭代一个像字符串或列表这样的可迭代对象。要使用 for 循环从字符串中删除引号,我们将使用以下步骤。
- 首先,我们将创建一个名为
quotes的列表来存储单引号和双引号字符。 - 然后,我们将创建一个名为
newStr的空字符串来存储输出字符串。 - 现在,我们将使用 for 循环遍历输入字符串中的字符。
- 在迭代过程中,如果我们发现除了单引号或双引号以外的字符,我们将使用字符串串联操作符将这些字符附加到
newStr中。为了检查一个字符是单引号还是双引号,我们将使用成员运算符。 - 如果我们在字符串中发现单引号或双引号字符,我们将跳过它。
- 在执行 for 循环之后,我们将在变量
newStr中获得输出字符串。
您可以在下面的示例中观察整个过程。
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
quotes = ["'", '"']
newStr = ""
for character in input_string:
if character not in quotes:
newStr += character
print("The output string is:", newStr)
输出:
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
不使用名为quotes的列表和成员操作符,我们可以直接比较字符串中出现单引号和双引号的字符。为此,我们将在 if 语句中使用等号运算符来比较字符。其余的过程与上面相同。
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
newStr = ""
for character in input_string:
if character == "'" or character == '"':
continue
else:
newStr += character
print("The output string is:", newStr)
输出:
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
在这里,您可以看到我们没有使用列表和成员操作符。相反,我们使用等号运算符直接比较了 if 语句中的字符。
在 Python 中使用 filter()函数和 join()方法移除字符串中的引号
filter()函数用于从 iterable 对象中排除元素。filter()函数的语法如下。
filter(input_function,iterable_object)
这里,
iterable_object是我们需要从中排除元素的 python 对象。input_function是一个接受iterable_object的一个元素并返回True或False的函数。
执行后,filter()函数返回一个filter对象。一个filter对象是一个可迭代的对象,它包含了input_function返回True的iterable_object的所有元素。
join() 方法用于从给定的 iterable 对象创建一个字符串。当在分隔符字符串上调用时, join() 方法将 iterable 对象作为其输入参数。
执行后,它返回一个字符串,其中 iterable 对象的所有元素都由分隔符分隔。
要使用 join()方法和filter()函数在 Python 中删除字符串中的引号,我们将使用以下步骤。
- 首先,我们将创建一个函数
isNotQuotes(),它将一个字符作为它的输入参数。如果字符是单引号或双引号字符,它返回False。否则,它返回True。 - 之后,我们将使用
filter()函数从字符串中排除引号。为此,我们将把isNotQuotes函数作为第一个输入参数,把输入字符串作为第二个参数传递给过滤函数。在执行了filter()函数之后,我们将得到一个filter对象,它包含输入字符串中除引号之外的所有字符。 - 现在,我们将使用
join()方法来获取输出字符串。为此,我们将使用空字符串作为分隔符。我们将调用分隔符上的join()方法,将 filter 对象作为它的输入参数。
在执行了join()方法之后,我们将得到没有任何引号的输出字符串。您可以在下面的示例中观察到这一点。
def isNotQuotes(character):
if character == '"':
return False
if character == "'":
return False
return True
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
filter_object=filter(isNotQuotes,input_string)
newStr = "".join(filter_object)
print("The output string is:", newStr)
输出:
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
使用列表理解删除 Python 中字符串的引号
列表理解用于从现有的可迭代对象创建一个新列表。在 Python 中,我们可以使用 list comprehension 和 join()方法来删除字符串中的引号。为此,我们将使用以下步骤。
- 首先,我们将创建一个名为
quotes的列表来存储单引号和双引号字符。 - 然后,我们将使用 list comprehension 从输入字符串中获取一个字符列表,不包括引号。
- 一旦我们获得了字符列表,我们将在一个空字符串上调用
join()方法,并将字符列表作为输入参数传递给它。 - 在执行了
join()方法之后,我们将得到想要的字符串。您可以在下面的示例中观察到这一点。
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
quotes = ["'", '"']
myList = [character for character in input_string if character not in quotes]
newStr = "".join(myList)
print("The output string is:", newStr)
输出:
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
在 Python 中使用 replace()方法移除字符串中的引号
replace()方法用于将字符串中的一个字符替换为另一个字符。在字符串上调用时,replace()方法将需要替换的元素作为第一个输入参数,新字符作为第二个参数。执行后,它返回修改后的字符串。
要使用 replace()方法在 Python 中删除字符串中的引号,我们将使用以下步骤。
- 首先,我们将对输入字符串调用
replace()方法。这里,我们将把单引号字符作为第一个输入参数,一个空字符串作为第二个输入参数传递给replace()方法。replace()方法将返回一个字符串tempStr作为输出。 - 同样,我们将调用
tempStr上的replace()方法。这一次,我们将把双引号字符作为第一个输入参数,一个空字符串作为第二个输入参数传递给replace()方法。
在第二次执行 replace 方法后,我们将得到所需的输出字符串,其中没有引号字符。您可以在下面的示例中观察到这一点。
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
tempStr = input_string.replace("'", "")
newStr = tempStr.replace('"', "")
print("The output string is:", newStr)
输出:
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
在 Python 中使用 re.sub()函数删除字符串中的引号
正则表达式为我们提供了各种字符串操作的函数。我们可以用 re。sub()Python 中移除字符串引号的函数。
re.sub()函数的语法如下。
re.sub(old_character, new_character, input_string)
这里,
input_string是我们需要替换或删除的字符串。old_character是需要从input_string中移除的字符。new_character是插入到input_string中代替old_character的字符。
为了使用re.sub()函数在 python 中删除给定字符串的引号,我们将使用单引号和双引号字符作为old_character,使用空字符串作为new_character。
- 首先,我们将把单引号作为第一个输入参数,一个空字符串作为第二个输入参数,给定的字符串作为第三个输入参数传递给
re.sub()函数。执行后,sub()函数将返回一个字符串。我们将把它命名为tempStr。 - 现在,我们将把双引号作为第一个输入参数,一个空字符串作为第二个输入参数,
tempStr作为第三个输入参数传递给re.sub()函数。
执行后,re.sub()函数将返回没有引号的字符串。您可以在下面的代码中观察到这一点。
import re
input_string = "Pythonf'orb''eginn'er's"
print("The input string is:", input_string)
tempStr = re.sub("'", "", input_string)
newStr = re.sub('"', "", tempStr)
print("The output string is:", newStr)
输出:
The input string is: Pythonf'orb''eginn'er's
The output string is: Pythonforbeginners
从 Python 字符串中移除第一个和最后一个引号字符
如果我们有一个只在开头和结尾有引号字符的字符串,如在"'Aditya'"或'"Aditya"'中,我们可以使用下面的方法从字符串中删除引号。
使用 ast 模块从字符串中删除第一个和最后一个引号字符
ast模块为我们提供了 literal_eval()函数来计算以字符串形式编写的表达式。literal_eval() 函数将一个字符串作为其输入参数,对其求值,然后返回输出。
当我们将字符串'"Aditya"'或"'Aditya'" 传递给literal_eval()函数时,它将输入字符串视为表达式,将"Aditya"或 'Aditya'视为相应的值。您可以在下面的示例中观察到这一点。
import ast
input_string = "'Aditya'"
newStr=ast.literal_eval(input_string)
print("The input string is:", input_string)
print("The output string is:", newStr)
输出:
The input string is: 'Aditya'
The output string is: Aditya
如果输入字符串在不同于第一个和最后一个位置的位置包含额外的引号,这种方法就不起作用。如果您试图使用literal_eval()函数从这样的输入字符串中删除引号,程序将运行到SyntaxError,如下例所示。
import ast
input_string = "'Adity'a'"
print("The input string is:", input_string)
newStr=ast.literal_eval(input_string)
print("The output string is:", newStr)
输出:
The input string is: 'Adity'a'
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 5, in <module>
newStr=ast.literal_eval(input_string)
File "/usr/lib/python3.8/ast.py", line 59, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.8/ast.py", line 47, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 1
'Adity'a'
^
SyntaxError: invalid syntax
在这种方法中,输入字符串的第一个和最后一个位置都必须包含引号字符。
如果我们在第一个位置有一个引用字符,而不是在最后一个位置,程序将运行到SyntaxError。类似地,如果我们在最后一个位置有一个引用字符,而不是在第一个位置,程序将再次运行到一个SyntaxError。
你可以在下面的例子中观察到这一点。
import ast
input_string = "'Aditya"
print("The input string is:", input_string)
newStr=ast.literal_eval(input_string)
print("The output string is:", newStr)
输出:
The input string is: 'Aditya
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 5, in <module>
newStr=ast.literal_eval(input_string)
File "/usr/lib/python3.8/ast.py", line 59, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.8/ast.py", line 47, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 1
'Aditya
^
SyntaxError: EOL while scanning string literal
需要记住的另一个条件是,字符串开头和结尾的引号字符应该相同。如果字符串的开头是单引号,结尾是双引号,反之亦然,程序将再次运行到如下所示的SyntaxError。
import ast
input_string = "'Aditya\""
print("The input string is:", input_string)
newStr=ast.literal_eval(input_string)
print("The output string is:", newStr)
输出:
The input string is: 'Aditya"
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 5, in <module>
newStr=ast.literal_eval(input_string)
File "/usr/lib/python3.8/ast.py", line 59, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python3.8/ast.py", line 47, in parse
return compile(source, filename, mode, flags,
File "<unknown>", line 1
'Aditya"
^
SyntaxError: EOL while scanning string literal
如果输入字符串的开头和结尾不包含引号字符,程序将会遇到一个ValueError异常。您可以在下面的示例中观察到这一点。
import ast
input_string = "Aditya"
print("The input string is:", input_string)
newStr = ast.literal_eval(input_string)
print("The output string is:", newStr)
输出:
The input string is: Aditya
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 5, in <module>
newStr = ast.literal_eval(input_string)
File "/usr/lib/python3.8/ast.py", line 99, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python3.8/ast.py", line 98, in _convert
return _convert_signed_num(node)
File "/usr/lib/python3.8/ast.py", line 75, in _convert_signed_num
return _convert_num(node)
File "/usr/lib/python3.8/ast.py", line 66, in _convert_num
_raise_malformed_node(node)
File "/usr/lib/python3.8/ast.py", line 63, in _raise_malformed_node
raise ValueError(f'malformed node or string: {node!r}')
ValueError: malformed node or string: <_ast.Name object at 0x7ffbe7ec60d0>
因此,您应该记住,只有当字符串只在开头和结尾包含引号字符时,才可以使用literal_eval()函数。
使用 eval()函数删除字符串中的第一个和最后一个引号字符
eval()功能的工作方式类似于 literal_eval()功能。它还将一个字符串表达式作为输入参数,对该表达式求值,并返回结果值。
您可以使用如下所示的eval()函数删除字符串的第一个和最后一个引号。
input_string = "'Aditya'"
print("The input string is:", input_string)
newStr = eval(input_string)
print("The output string is:", newStr)
输出:
The input string is: 'Aditya'
The output string is: Aditya
针对string_eval()功能提到的所有条件对于eval() 功能都是真实的。因此,你应该记住你不能对每个字符串使用eval()函数。
使用 json 模块从字符串中删除第一个和最后一个引号字符
双引号中的 python 字符串是有效的 json 对象。因此,我们可以使用 json 模块从输入字符串的第一个和最后一个位置移除引号。
json 模块中的 loads() 函数将一个 json 对象作为其输入参数,并返回一个对应于 JSON 对象的 python 字符串。
因为我们的字符串在第一个和最后一个位置包含额外的引号。它将被视为有效的 json 对象。因此,我们可以将它传递给loads()函数,以获得如下所示的输出字符串。
import json
input_string = '"Aditya"'
print("The input string is:", input_string)
newStr = json.loads(input_string)
print("The output string is:", newStr)
输出:
The input string is: "Aditya"
The output string is: Aditya
这里,您应该记住,带单引号的字符串不是有效的 json 字符串。因此,如果您试图使用 json 模块从给定的字符串中删除单引号,程序将会出错,如下例所示。
import json
input_string = "'Aditya'"
print("The input string is:", input_string)
newStr = json.loads(input_string)
print("The output string is:", newStr)
输出:
The input string is: 'Aditya'
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 4, in <module>
newStr = json.loads(input_string)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
在除了额外的双引号之外的所有其他情况下,如果您试图从字符串中删除引号,使用 json 模块的方法将会出错。因此,您应该记住,您只能在一种情况下使用这种方法。
使用 strip()函数删除字符串中的第一个和最后一个引号字符
使用 ast 模块、json 模块或eval()函数来删除字符串开头和结尾的引号有很多限制。使用这些方法时,您的程序很可能会遇到异常。除了上述方法,我们可以使用strip() 方法从字符串的开头和结尾删除引号。
strip()方法在字符串上调用时,将一个字符作为其输入参数。执行后,它从字符串的开头和结尾删除该字符的所有匹配项,并返回一个新字符串。
要删除字符串开头和结尾的引号,我们将使用下面的方法。
- 首先,我们将声明一个字符串
temp1,并将其初始化为输入字符串。 - 现在,我们将使用 while 循环来删除引号字符。在 while 循环中,我们将使用以下步骤。
- 首先,我们将声明一个名为
temp2的临时字符串,并将其初始化为temp1。 - 现在,我们将调用
temp1上的strip()方法。这里,我们将把一个单引号字符作为输入参数传递给strip()方法。我们将在temp3中存储strip()方法的返回值。 - 同样,我们将调用
temp3上的strip()方法。这一次,我们将把双引号作为输入参数传递给strip()方法。我们将输出存储在temp4中。 - 现在,我们将检查
temp4是否等于temp2。如果是,则所有的引号都已从字符串中删除,因为在当前迭代中字符串没有发生变化。因此,我们将使用 break 语句退出 while 循环。 - 如果
temp2不等于temp4,字符串的开头和结尾仍然包含引号。因此,我们需要另一个迭代。为此,我们将把temp4分配给temp1。
在执行 while 循环之后,我们将获得所需的字符串,并从其开始和结束处删除引号。您可以在下面的代码中观察到这一点。
input_string = "'Pythonforbeginners'"
print("The input string is:", input_string)
temp1 = input_string
while True:
temp2 = temp1
tem3 = temp2.strip("'")
temp4 = tem3.strip('"')
if temp4 == temp2:
newStr = temp2
print("The output string is:", newStr)
break
else:
temp1 = temp4
输出:
The input string is: 'Pythonforbeginners'
The output string is: Pythonforbeginners
在literal_eval()方法和 eval()函数失败的情况下,这种方法可以成功地删除引号。因此,您可以自由使用这种方法。例如,看看下面的例子。
input_string = "'''''''Pythonforbeginners'\""
print("The input string is:", input_string)
temp1 = input_string
while True:
temp2 = temp1
tem3 = temp2.strip("'")
temp4 = tem3.strip('"')
if temp4 == temp2:
newStr = temp2
print("The output string is:", newStr)
break
else:
temp1 = temp4
输出:
The input string is: '''''''Pythonforbeginners'"
The output string is: Pythonforbeginners
在上面的例子中,您可以观察到我们使用了一个输入字符串,它的左边包含七个单引号,右边包含一个带双引号的单引号。即使在这种不对称的情况下,程序也能正确工作,不会遇到任何错误。
结论
在本文中,我们讨论了在 Python 中从字符串中移除引号的各种方法。在所有这些方法中,我建议您使用replace()方法和 re.sub() 函数。使用这些函数的方法是最有效的。
我希望你喜欢阅读这篇文章。想要了解更多关于 python 编程的知识,你可以阅读这篇关于 Python 中字典理解的文章。你可能也会喜欢这篇关于机器学习中回归的文章。
在 Python 中从字符串中移除子字符串
原文:https://www.pythonforbeginners.com/basics/remove-substring-from-string-in-python
在 python 中处理文本数据时,我们有时需要从文本中移除特定的子串。在本文中,我们将讨论在 Python 中从字符串中移除子串的不同方法。
使用 split()方法从 Python 中的字符串中移除子字符串
Python 中的split() 方法用于在分隔符处将字符串分割成子字符串。当在字符串上调用split()方法时,它以分隔符的形式接受一个字符串作为它的输入参数。执行后,它从原始字符串中返回一个子字符串列表,该子字符串在分隔符处拆分。
要使用split()方法从 Python 中的字符串中删除子串,我们将使用以下步骤。
- 首先,我们将创建一个名为
output_string的空字符串来存储输出字符串。 - 然后,我们将使用
split()方法从需要移除特定子串的位置将字符串分割成子串。为此,我们将调用输入字符串上的split()方法,将需要删除的子字符串作为输入参数。执行后,split()方法将返回一串子字符串。我们将把这个列表分配给一个变量str_list。 - 一旦我们得到了字符串列表,我们将使用 for 循环遍历
str_list中的子字符串。在迭代过程中,我们将使用字符串串联操作将当前子字符串添加到output_string中。
在执行 for 循环后,我们将在变量output_string中获得所需的输出字符串。您可以在下面的代码中观察到这一点。
myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
output_string = ""
str_list = myStr.split(substring)
for element in str_list:
output_string += element
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)
输出:
The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free tutorials for you to learn .
在输出中,您可以观察到子字符串python已经从输入字符串中删除。
使用 join()方法在 Python 中移除字符串中的子字符串
多次执行字符串连接需要不必要的存储和时间。因此,我们可以通过使用 join() 方法来避免这种情况。
当在分隔符字符串上调用时,join()方法将 iterable 对象作为其输入参数。执行后,它返回一个字符串,该字符串由分隔符字符串分隔的 iterable 对象的元素组成。
要使用join()方法从 python 中的字符串中删除 substring,我们将使用以下步骤。
- 首先,我们将使用
split()方法将输入字符串从需要删除特定子字符串的位置分割成子字符串。为此,我们将调用输入字符串上的split()方法,将需要删除的子字符串作为输入参数。执行后,split()方法将返回一串子字符串。我们将把这个列表分配给一个变量str_list。 - 接下来,我们将调用空字符串上的
join()方法,将str_list作为其输入参数。
在执行了 join()方法之后,我们将得到所需的字符串输出,如下所示。
myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
str_list = myStr.split(substring)
output_string = "".join(str_list)
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)
输出:
The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free tutorials for you to learn .
在这里,您可以观察到我们已经使用 join()方法将由split()方法返回的列表转换成了一个字符串。因此,我们避免了重复的字符串连接,就像我们在前面的例子中所做的那样。
使用 replace()方法从 Python 中的字符串中移除子字符串
在 python 中,replace()方法用于替换字符串中的一个或多个字符。当在一个字符串上调用时,replace()方法将两个子字符串作为它的输入参数。执行后,它将第一个参数中的子字符串替换为第二个输入参数中的子字符串。然后它返回修改后的字符串。
为了使用replace()方法从字符串中删除子串,我们将调用原始字符串上的replace() 方法,将要删除的子串作为第一个输入参数,一个空字符串作为第二个输入参数。
在执行了replace()方法之后,我们将得到如下例所示的输出字符串。
myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
output_string = myStr.replace(substring, "")
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)
输出:
The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free tutorials for you to learn .
这里,我们使用replace()方法在一个语句中从输入字符串中删除了所需的子字符串。
使用正则表达式从 python 化的字符串中删除子串
正则表达式为我们提供了在 Python 中操作字符串的有效方法。在 python 中,我们还可以使用正则表达式从字符串中删除子串。为此,我们可以使用re.split() 方法和re.sub()方法。
使用 re.split()方法在 Python 中移除字符串中的子字符串
方法用于在指定的分隔符处分割文本。re.split()方法将分隔符字符串作为第一个输入参数,将文本字符串作为第二个输入参数。执行后,它返回由分隔符分隔的原始字符串列表。
要使用re.split()方法从 Python 中的字符串中删除子串,我们将使用以下步骤。
- 首先,我们将创建一个名为
output_string的空字符串来存储输出字符串。 - 然后,我们将使用
re.split()方法从需要移除特定子串的位置将字符串分割成子串。为此,我们将执行re.split()方法,将需要删除的子字符串作为第一个输入参数,将文本字符串作为第二个输入参数。执行后,re.split()方法将返回一串子字符串。我们将把这个列表分配给一个变量str_list。 - 一旦我们得到了字符串列表,我们将使用 for 循环遍历
str_list中的子字符串。在迭代过程中,我们将使用字符串连接操作将当前子字符串添加到output_string。
在执行 for 循环后,我们将在变量output_string中获得所需的输出字符串。您可以在下面的代码中观察到这一点。
import re
myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
output_string = ""
str_list = re.split(substring, myStr)
for element in str_list:
output_string += element
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)
输出:
The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free tutorials for you to learn .
您可以观察到使用re.split()方法的方法与使用 string split()方法的方法几乎相似。但是,这两种方法的执行速度不同。如果输入字符串非常大,那么应该首选re.split()方法来拆分输入字符串。
多次执行字符串连接需要不必要的内存和时间。因此,我们可以通过使用 join()方法来避免这种情况。
要使用join()方法从 python 中的字符串中删除 substring,我们将使用以下步骤。
-
首先,我们将使用
re.split()方法将输入字符串从需要删除特定子字符串的位置分割成子字符串。为此,我们将执行re.split()方法,将需要删除的子字符串作为第一个输入参数,将文本字符串作为第二个输入参数。执行后,re.split()方法将返回一串子字符串。我们将把这个列表分配给一个变量str_list。 -
接下来,我们将调用空字符串上的
join()方法,将str_list作为其输入参数。
在执行了join()方法之后,我们将得到所需的字符串输出,如下所示。
import re
myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
str_list = re.split(substring, myStr)
output_string = "".join(str_list)
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)
输出:
The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free tutorials for you to learn .
在这种方法中,我们仅用两条 python 语句就获得了输出字符串。此外,我们没有做重复的字符串连接,这需要不必要的时间。
使用 re.sub()方法从 Python 中的字符串中移除子字符串
在 python 中,re.sub()方法用于替换字符串中的一个或多个字符。re.sub()方法有三个输入参数。第一个输入参数是需要替换的子字符串。第二个输入参数是替代子串。原始字符串作为第三个输入字符串传递。
执行后,re.sub()方法用第二个输入参数的子字符串替换第一个参数中的子字符串。然后它返回修改后的字符串。
为了使用re.sub() 方法从字符串中删除子串,我们将执行re.sub() 方法,将要删除的子串作为第一个输入参数,一个空字符串作为第二个输入参数,原始字符串作为第三个输入参数。
在执行了re.sub()方法之后,我们将得到如下例所示的输出字符串。
import re
myStr = "I am PFB. I provide free python tutorials for you to learn python."
substring = "python"
output_string = re.sub(substring, "", myStr)
print("The input string is:", myStr)
print("The substring is:", substring)
print("The output string is:", output_string)
输出:
The input string is: I am PFB. I provide free python tutorials for you to learn python.
The substring is: python
The output string is: I am PFB. I provide free tutorials for you to learn .
re.sub()方法的工作方式类似于replace() 方法。但是,它比后者更快,应该是首选。
通过索引移除 Python 中字符串的子串
有时,当我们知道子串在字符串中的位置时,我们可能需要从字符串中移除子串。为了在 python 中通过索引从字符串中移除子串,我们将使用字符串切片。
如果我们必须从索引 I 到 j 中移除子串,我们将制作两个字符串片段。第一个片段将从索引 0 到 i-1,第二个片段将从索引 j+1 到最后一个字符。
获得切片后,我们将连接切片以获得输出字符串,如下例所示。
import re
myStr = "I am PFB. I provide free python tutorials for you to learn python."
output_string = myStr[0:5]+myStr[11:]
print("The input string is:", myStr)
print("The output string is:", output_string)
输出:
The input string is: I am PFB. I provide free python tutorials for you to learn python.
The output string is: I am provide free python tutorials for you to learn python.
结论
在本文中,我们讨论了用 Python 从字符串中删除子串的不同方法。在所有方法中,使用re.sub()方法和replace()方法的方法具有最好的时间复杂度。因此,我建议你在你的程序中使用这些方法。
我希望你喜欢阅读这篇文章。要了解更多关于 python 编程的知识,您可以阅读这篇关于如何在 Python 中删除列表中所有出现的字符的文章。您可能也喜欢这篇关于如何检查 python 字符串是否包含数字的文章。
在 Python 中从列表中移除第一个元素
原文:https://www.pythonforbeginners.com/basics/remove-the-first-element-from-a-list-in-python
列表是 python 中最常用的数据结构之一。在 python 中,我们有不同的方法来对列表执行操作。在这篇文章中,我们将看看使用不同的方法从列表中删除第一个元素的不同方法,如切片、pop()方法、remove()方法和 del 操作。
使用切片从列表中移除第一个元素
在 python 中,切片是创建字符串或列表的一部分的操作。通过切片,我们可以访问任何字符串、元组或列表的不同部分。为了对名为 myList 的列表执行切片,我们使用语法myList[start, end, difference],其中“start”和“end”分别是切片列表在原始列表中开始和结束的索引。“差异”用于选择序列中的元素。从索引=“开始+n *差异”的列表中选择元素,其中 n 是整数,并且索引应该小于“结束”。
为了使用切片来移除列表的第一个元素,我们将从第二个元素开始取出子列表,并留下第一个元素。因此,第一个元素将从列表中删除。这可以如下进行。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Original List is:", myList)
myList = myList[1::1]
print("List after modification is:", myList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
List after modification is: [2, 3, 4, 5, 6, 7]
使用 pop()方法从列表中移除第一个元素
pop()方法用于从指定的索引中移除列表中的任何元素。它将元素的索引作为可选的输入参数,并在从列表中删除元素后,返回指定索引处的元素。如果没有传递输入参数,它将在删除后返回列表的最后一个元素。
要使用 pop()方法删除列表的第一个元素,我们将调用列表上的 pop()方法,并将传递第一个元素的索引,即 0 作为输入。从列表中删除后,它将返回列表的第一个元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Original List is:", myList)
myList.pop(0)
print("List after modification is:", myList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
List after modification is: [2, 3, 4, 5, 6, 7]
使用 remove()方法
remove()方法用于删除列表中第一个出现的元素。调用 remove()方法时,它将从列表中删除的元素作为输入,并从列表中删除该元素。当元素不在列表中时,它会引发 ValueError。为了处理 ValueError,您可以使用除了块之外的 python try 来使用异常处理。
要使用 remove()方法删除列表的第一个元素,我们将使用其索引(即 0)来访问列表的第一个元素。然后我们将元素作为参数传递给 remove()方法。这将删除列表的第一个元素,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Original List is:", myList)
element = myList[0]
myList.remove(element)
print("List after modification is:", myList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
List after modification is: [2, 3, 4, 5, 6, 7]
使用 del 关键字从列表中删除第一个元素
python 中的 del 关键字用于删除对象。在 python 中,每个变量都指向一个对象。我们知道列表的第一个元素指向内存中的一个对象,我们也可以使用 del 关键字删除它,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7]
print("Original List is:", myList)
del myList[0]
print("List after modification is:", myList)
输出:
Original List is: [1, 2, 3, 4, 5, 6, 7]
List after modification is: [2, 3, 4, 5, 6, 7]
结论
在本文中,我们看到了用 python 从列表中删除第一个元素的不同方法。我们使用了切片、pop()方法、remove()方法和 del 关键字来删除列表中的第一个元素。要了解更多关于列表的知识,你可以阅读这篇关于列表理解的文章。请继续关注更多内容丰富的文章。
从字符串中删除空白字符
原文:https://www.pythonforbeginners.com/basics/remove-whitespace-characters-from-a-string
python 中的字符串广泛用于处理文本数据。在这篇文章中,我们将研究从字符串中删除空白字符的不同方法。我们还将实现这些示例,以便更好地理解这个概念。
什么是空白字符?
空白字符是诸如空格、制表符和换行符之类的字符。在 python 中,定义了一个包含所有空白字符的字符串常量 string.whitespace 。这些字符是由“”表示的空格、由“\t”表示的制表符、由“\n”表示的换行符、由“\r”表示的回车符、由“\v”表示的垂直制表符和由“\f”表示的换页符。
现在我们来看看从字符串中删除这些空白字符的不同方法。
使用 for 循环删除空白字符
从字符串中删除空白字符的最简单的方法是使用 for 循环。在这个方法中,我们将首先创建一个新的空字符串。之后,对于输入字符串中的每个字符,我们将检查它是否是空白字符。如果是,我们将丢弃它。否则,我们将使用如下的字符串连接操作将字符添加到新创建的字符串中。
import string
input_string = """This is PythonForBeginners.com
Here, you can read python \v tutorials for free."""
new_string = ""
for character in input_string:
if character not in string.whitespace:
new_string = new_string + character
print("THe original string is:")
print(input_string)
print("Output String is:")
print(new_string)
输出:
THe original string is:
This is PythonForBeginners.com
Here, you can read python tutorials for free.
Output String is:
ThisisPythonForBeginners.comHere,youcanreadpythontutorialsforfree.
使用 split()方法删除空白字符
我们可以使用 split()和 join()方法来删除空格,而不是遍历输入字符串的每个字符。
在字符串上调用 split()方法时,该方法在空格处拆分字符串,并返回子字符串列表。我们可以使用 join()方法连接所有的子字符串。
join()方法在分隔符字符串上调用时,接受包含字符串的列表、元组或其他可迭代对象,并用分隔符字符串连接可迭代对象中的所有字符串。这里,我们将使用空字符串作为分隔符字符串。这样,我们可以将 split()方法创建的所有子字符串连接起来,以创建输出字符串。
import string
input_string = """This is PythonForBeginners.com
Here, you can read python \v tutorials for free."""
str_list = input_string.split()
new_string = "".join(str_list)
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
输出:
The original string is:
This is PythonForBeginners.com
Here, you can read python tutorials for free.
Output String is:
ThisisPythonForBeginners.comHere,youcanreadpythontutorialsforfree.
使用正则表达式删除空白字符
在 python 中,我们可以使用 regex 模块中的 sub()方法用一个模式替换另一个模式。sub()方法接受三个输入参数。第一个输入是需要替换的模式。第二个输入参数是必须放在字符串中的新模式。第三个输入参数是输入字符串。它返回一个带有修改值的新字符串。
这里,我们将用原始字符串中的空字符串替换中的空格字符。匹配所有空格字符的正则表达式是“\s+”。新的模式将只是一个由""表示的空字符串。使用这些模式和 sub()方法,我们可以从输入字符串中删除空白字符,如下所示。
import re
import string
input_string = """This is PythonForBeginners.com
Here, you can read python \v tutorials for free."""
new_string = re.sub(r"\s+", "", input_string)
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
输出:
The original string is:
This is PythonForBeginners.com
Here, you can read python tutorials for free.
Output String is:
ThisisPythonForBeginners.comHere,youcanreadpythontutorialsforfree.
使用翻译表删除空白字符
除了正则表达式,我们还可以使用翻译表和 translate()方法来删除字符串中的所有空白字符。
翻译表就是包含旧字符到新字符映射的字典。在我们的程序中,我们将把每个空格字符映射到一个空字符串。这里,我们将使用空格字符的 ASCII 值作为键,空字符串作为它们的关联值。使用 order()函数可以找到每个字符的 ASCII 值。可以如下创建转换表。
import string
translation_table = {ord(x): "" for x in string.whitespace}
print("The translation table is:")
print(translation_table)
输出:
The translation table is:
{32: '', 9: '', 10: '', 13: '', 11: '', 12: ''}
创建翻译表后,我们可以使用 translate()方法从输入字符串中删除空白字符。在字符串上调用 translate()方法时,该方法将翻译表作为输入,并使用翻译表替换其中的字符。
我们将使用上面创建的转换表用空字符串替换空白字符,如下所示。
import string
input_string = """This is PythonForBeginners.com
Here, you can read python \v tutorials for free."""
translation_table = {ord(x): "" for x in string.whitespace}
new_string = input_string.translate(translation_table)
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
输出:
The original string is:
This is PythonForBeginners.com
Here, you can read python tutorials for free.
Output String is:
ThisisPythonForBeginners.comHere,youcanreadpythontutorialsforfree.
结论
在本文中,我们讨论了从字符串中删除空白字符的不同方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
在数据帧中按索引重命名列
原文:https://www.pythonforbeginners.com/basics/rename-column-by-index-in-dataframes
在 python 中,数据帧用于处理表格数据。在本文中,我们将讨论如何通过 python 中的数据帧中的索引来重命名列。
使用索引号更改列名
我们可以使用“columns”属性访问数据帧中的列名。数据帧的 columns 属性包含一个Index对象。Index对象包含一个列名列表,如下例所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
您可以使用Index对象的 ‘values’属性来访问列名数组,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
print("The columns are:")
print(df.columns.values)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
The columns are:
['Name' 'Roll' 'Language']
要在数据帧中通过索引重命名列,我们可以在 values 属性中修改数组。例如,您可以使用值数组的索引 0 来更改第一列的名称,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
print("The columns are:")
print(df.columns.values)
df.columns.values[0]="First Name"
print("The modified column object is:")
print(df.columns)
print("The modified columns are:")
print(df.columns.values)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
The columns are:
['Name' 'Roll' 'Language']
The modified column object is:
Index(['First Name', 'Roll', 'Language'], dtype='object')
The modified columns are:
['First Name' 'Roll' 'Language']
在这种方法中,我们不能一次更改多个列名。要更改多个列名,需要逐个重命名每个列名,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
print("The columns are:")
print(df.columns.values)
df.columns.values[0]="First Name"
df.columns.values[1]="Roll Number"
print("The modified column object is:")
print(df.columns)
print("The modified columns are:")
print(df.columns.values)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
The columns are:
['Name' 'Roll' 'Language']
The modified column object is:
Index(['First Name', 'Roll Number', 'Language'], dtype='object')
The modified columns are:
['First Name' 'Roll Number' 'Language']
我们还可以使用 rename()方法通过索引一次更改多个列名。让我们来讨论这种方法。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
在数据帧中使用 rename()方法更改列名
我们可以使用rename() 方法通过索引号来重命名多个列。当在 dataframe 上调用时,rename() 方法将一个字典作为它的输入参数。字典应该包含需要重命名为键的列名。新的列名应该是与原始键相关联的值。执行之后,rename()方法返回一个新的数据帧,其中包含修改后的列名。
为了使用索引号和rename()方法修改列名,我们将首先使用 dataframe 的columns.values 属性获得列名数组。之后,我们将创建一个字典,其中列名作为键,新列名作为键的关联值。然后,我们将把字典传递给rename() 方法。执行后,rename()方法将返回修改了列名的 dataframe,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The column object is:")
print(df.columns)
print("The columns are:")
print(df.columns.values)
nameDict={"Name":"First Name","Roll":"Roll No."}
df=df.rename(columns=nameDict)
print("The modified column object is:")
print(df.columns)
print("The modified columns are:")
print(df.columns.values)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The column object is:
Index(['Name', 'Roll', 'Language'], dtype='object')
The columns are:
['Name' 'Roll' 'Language']
The modified column object is:
Index(['First Name', 'Roll No.', 'Language'], dtype='object')
The modified columns are:
['First Name' 'Roll No.' 'Language']
结论
在本文中,我们讨论了如何在 python 中通过索引重命名数据帧中的列。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
用 Python 重命名数据帧中的列
原文:https://www.pythonforbeginners.com/basics/rename-columns-in-a-dataframe-in-python
Pandas 数据帧是 python 中处理表格数据的最有效的数据结构之一。当我们将表格数据从 csv 文件导入数据帧时,我们通常需要重命名数据帧中的列。在本文中,我们将讨论如何在 python 中重命名数据帧中的列。
使用 Rename()方法重命名 DataFrame 列
pandas 模块为我们提供了rename()方法来重命名数据帧中的列。在 dataframe 上调用rename()方法时,该方法将一个 python 字典作为其第一个输入参数。字典中的键应该由要重命名的列的原始名称组成。与键相关联的值应该是新的列名。执行后,rename()方法返回一个新的带有修改名称的数据帧。例如,我们可以使用rename()方法重命名给定数据帧的‘Roll’列,如下例所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The original column names are:")
print(df.columns.values)
nameDict={"Roll":"Roll No."}
df=df.rename(columns=nameDict)
print("The modified column names are:")
print(df.columns.values)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The original column names are:
['Name' 'Roll' 'Language']
The modified column names are:
['Name' 'Roll No.' 'Language']
如果您想要重命名数据帧中的多个列,您可以在字典中传递旧的列名和新的列名,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The original column names are:")
print(df.columns.values)
nameDict={"Name":"Person","Roll":"Roll No."}
df=df.rename(columns=nameDict)
print("The modified column names are:")
print(df.columns.values)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The original column names are:
['Name' 'Roll' 'Language']
The modified column names are:
['Person' 'Roll No.' 'Language']
在上面的例子中,原始列中的列名没有被修改。相反,我们得到一个新的数据帧,其中包含修改后的列名。
您还可以重命名原始数据框架的列。为此,我们将使用rename()方法的‘inplace’ 参数。‘inplace’参数采用一个可选的输入参数,它有默认值False。因此,原始数据帧中的列名不会被修改。您可以将‘inplace’参数设置为值True来修改原始数据帧的列名,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The original column names are:")
print(df.columns.values)
nameDict={"Name":"Person","Roll":"Roll No."}
df.rename(columns=nameDict,inplace=True)
print("The modified column names are:")
print(df.columns.values)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The original column names are:
['Name' 'Roll' 'Language']
The modified column names are:
['Person' 'Roll No.' 'Language']
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
使用列名列表重命名数据框架列
如果必须一次重命名数据帧的所有列,可以使用 python 列表来完成。为此,我们只需将包含新数据帧名称的列表分配给数据帧的‘columns’ 属性,如下所示。
import pandas as pd
import numpy as np
df=pd.read_csv("demo_file.csv")
print("The dataframe is:")
print(df)
print("The original column names are:")
print(df.columns.values)
df.columns=['Person', 'Roll No.', 'Language']
print("The modified column names are:")
print(df.columns.values)
输出:
The dataframe is:
Name Roll Language
0 Aditya 1 Python
1 Sam 2 Java
2 Chris 3 C++
3 Joel 4 TypeScript
The original column names are:
['Name' 'Roll' 'Language']
The modified column names are:
['Person' 'Roll No.' 'Language']
结论
在本文中,我们讨论了如何用 python 重命名数据帧中的列。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
重命名熊猫系列中的索引
原文:https://www.pythonforbeginners.com/basics/rename-index-in-a-pandas-series
我们使用 pandas 系列对象来完成 python 中的各种数据处理任务。在本文中,我们将讨论如何重命名熊猫系列中的索引。
使用 Index 属性重命名熊猫系列中的索引
创建系列时,索引的名称为空。要重命名系列的索引,可以使用 series index 对象的name属性。您可以将新的索引名称分配给 index 对象的name属性,以重命名序列索引,如下所示。
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)
series.index.name="Numbers"
print("The series is:")
print(series)
输出:
The series is:
Numbers
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在上面的例子中,我们首先使用Series()构造函数创建了一个熊猫系列。然后,我们将字符串"Numbers"分配给熊猫系列的 index.name 属性。因此,系列索引被重命名为"Numbers"。
要重命名系列的索引,也可以使用rename_axis() 方法。
使用 rename_axis()方法重命名系列的索引
rename_axis()方法的语法如下。
Series.rename_axis(mapper=_NoDefault.no_default, *, inplace=False, **kwargs)
这里,
mapper参数将索引的新名称作为其输入参数。- 默认情况下,
rename_axis()方法返回一个新的 series 对象。要修改调用了rename_axis()方法的原始序列,可以将inplace参数设置为True。
执行后,rename_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,index=numbers)
series=series.rename_axis("Numbers")
print("The series is:")
print(series)
输出:
The series is:
Numbers
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在上面的例子中,我们首先创建了一个系列。然后,我们使用rename_axis()方法重命名系列的索引列。这里,rename_axis() 方法返回一个新的序列,而不是修改原来的序列。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇 MLFlow 教程,里面有代码示例。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
在 Python 中就地重命名系列中的索引
您也可以修改原始序列,而不是在重命名索引后创建新的序列对象。为此,您可以在如下所示的rename_axis()方法中将inplace参数设置为 True。
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)
series.rename_axis("Numbers",inplace=True)
print("The series is:")
print(series)
输出:
The series is:
Numbers
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
在本例中,我们已经将rename_axis()参数中的inplace参数设置为真。因此,原始系列的索引已被重命名,而不是创建一个新系列。
结论
在本文中,我们讨论了如何使用 index 属性和 renam_axis()方法重命名 pandas 系列中的索引。要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
重命名数据框架中的特定列
原文:https://www.pythonforbeginners.com/basics/rename-specific-columns-in-dataframe
Pandas Dataframes 用于处理 python 中的表格数据。在本文中,我们将讨论如何在 python 中重命名数据帧中的特定列。
通过索引重命名数据帧中的特定列
我们可以使用'columns'属性访问 pandas 数据帧中的列名。在 dataframe 对象上调用'columns'属性时,会返回一个索引对象。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
columns = df1.columns
print("The column object is:")
print(columns)
输出:
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 object is:
Index(['Name', 'Roll Number', ' Subject'], dtype='object')
Index 对象包含'values'属性,其中所有的列名都存储在一个数组中,如下所示。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe is:")
print(df1)
columns = df1.columns
print("The column object is:")
print(columns)
print("The column value is")
print(columns.values)
输出:
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 object is:
Index(['Name', 'Roll Number', ' Subject'], dtype='object')
The column value is
['Name' 'Roll Number' ' Subject']
要重命名数据帧中的特定列,我们可以更改值数组的元素。例如,我们可以将值数组中的值“Roll Number”更改为“Registration Number”,如下所示。
df1.columns.values[1] = "Registration Number"
上述变化反映在熊猫数据框架的列名中。因此,数据帧中的“Roll Number”列名将更改为“Registration Number”列名。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe before modification is:")
print(df1)
df1.columns.values[1] = "Registration Number"
print("The dataframe after modification is:")
print(df1)
输出:
The dataframe before modification 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 dataframe after modification is:
Name Registration Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
若要一次更改多个列名,还可以更改值数组中的多个值。这种变化也将反映在数据帧中。
建议阅读:机器学习中的回归
使用 Rename()方法重命名数据帧中的特定列
我们可以使用rename()方法来重命名 dataframe 中的特定列,而不是使用“values”数组。在 dataframe 上调用rename()方法时,该方法将一个字典映射作为其输入参数。映射应该包含需要重命名为 key 的列名,新的列名应该是与字典中的键相关联的值。执行后,rename()方法将返回一个新的 dataframe,其中输入字典中给定的特定列被重命名。您可以在下面的示例中观察到这一点。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe before modification is:")
print(df1)
new_df = df1.rename(columns={'Roll Number': "Registration Number"})
print("The dataframe after modification is:")
print(new_df)
输出:
The dataframe before modification 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 dataframe after modification is:
Name Registration Number Subject
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
要重命名多个列,可以在作为输入参数提供给rename()方法的 python 字典中将多个列名及其相应的更改名称作为键-值对传递,如下所示。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe before modification is:")
print(df1)
new_df = df1.rename(columns={' Subject': "Language", 'Roll Number': "Registration Number"})
print("The dataframe after modification is:")
print(new_df)
输出:
The dataframe before modification 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 dataframe after modification is:
Name Registration Number Language
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
您也可以使用rename()方法更改现有数据框架的列名,而不是创建一个列名已更改的新数据框架。为此,我们将使用rename()方法的参数inplace。'inplace'参数有默认值False,这意味着原始数据帧没有被修改,在重命名列后返回一个新的数据帧。要修改原始 dataframe 的列名,可以将值True作为输入变量传递给'inplace'参数,如下所示。
import pandas as pd
df1 = pd.read_csv('student_details.csv')
print("The dataframe before modification is:")
print(df1)
df1.rename(columns={' Subject': "Language", 'Roll Number': "Registration Number"},inplace=True)
print("The dataframe after modification is:")
print(df1)
输出:
The dataframe before modification 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 dataframe after modification is:
Name Registration Number Language
0 Aditya 12 Python
1 Sam 23 Java
2 Chris 11 C++
3 Joel 10 JavaScript
4 Mayank 5 Typescript
在上面的示例中,您可以观察到在使用'inplace'参数后,原始数据帧已经被修改。
结论
在本文中,我们讨论了重命名数据帧中特定列的各种方法。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于用 python 理解字典的文章。
请继续关注更多内容丰富的文章。快乐学习!
在 Python 中重复列表中的每个元素
原文:https://www.pythonforbeginners.com/lists/repeat-each-element-in-a-list-in-python
在 python 中,我们为各种任务使用列表。我们已经讨论了列表上的各种操作,比如计算列表中元素的频率或者反转列表。在本文中,我们将讨论三种在 python 中使列表中的每个元素重复 k 次的方法。
Python 中如何将一个列表中的每个元素重复 k 次?
为了在 python 中重复列表中的元素,我们将一个给定列表的元素重复插入到一个新列表中。为了让列表中的每个元素重复 k 次,我们将把现有 k 次的每个元素插入到新列表中。
例如,如果我们有一个列表myList=[1,2,3,4,5],我们必须重复列表的元素两次,输出列表将变成[1,1,2,2,3,3,4,4,5, 5]。
为了执行这个操作,我们可以用来循环或者用append()方法来列表理解。或者,我们可以使用 itertools.chain.from_iterable()和itertools.repeat()方法。我们将在接下来的章节中讨论每一种方法。
使用 For 循环和 append()方法将列表中的每个元素重复 k 次
方法用于将元素添加到列表的末尾。当在列表上调用时,append()方法获取一个元素并将其添加到列表中,如下所示。
myList = [1, 2, 3, 4, 5]
print("The original list is:", myList)
element = 6
myList.append(element)
print("List after appending {} is: {}".format(element, myList))
输出:
The original list is: [1, 2, 3, 4, 5]
List after appending 6 is: [1, 2, 3, 4, 5, 6]
为了让列表中的每个元素重复 k 次,我们将首先创建一个名为newList的空列表。之后,我们将遍历输入列表的每个元素。在遍历过程中,我们将使用 for 循环、range()方法和append()方法将现有列表的每个元素添加到新创建的列表中 k 次。执行 for 循环后,输入列表的每个元素将在新列表中重复 k 次,如下例所示。
myList = [1, 2, 3, 4, 5]
print("The original list is:", myList)
k = 2
newList = []
for element in myList:
for i in range(k):
newList.append(element)
print("The output list is:", newList)
输出:
The original list is: [1, 2, 3, 4, 5]
The output list is: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
使用列表理解将列表中的每个元素重复 k 次
除了使用 for 循环,我们可以使用 list comprehension 将列表中的每个元素重复 k 次,如下所示。
myList = [1, 2, 3, 4, 5]
print("The original list is:", myList)
k = 2
newList = [element for element in myList for i in range(k)]
print("The output list is:", newList)
输出:
The original list is: [1, 2, 3, 4, 5]
The output list is: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
使用 itertools.chain.from_iterable()和 itertools.repeat()方法
我们可以使用itertools.chain.from_iterable()和itertools.repeat()方法将列表中的每个元素重复 k 次,而不是显式地将元素添加到新列表中来重复它们。
itertools.repeat()方法将一个值和该值必须重复的次数作为输入参数,并创建一个迭代器。例如,我们可以创建一个迭代器,它重复任意给定值五次,如下所示。
import itertools
element = 5
k = 10
newList = list(itertools.repeat(element, k))
print("The output list is:", newList)
输出:
The output list is: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
itertools.chain.from_iterable()获取可迭代对象的列表,并使用作为参数传递的可迭代对象的所有元素创建一个迭代器,如下所示。
import itertools
myList1 = [1, 2, 3, 4, 5]
myList2 = [6, 7, 8, 9, 10]
newList = list(itertools.chain.from_iterable([myList1, myList2]))
print("The output list is:", newList)
输出:
The output list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
为了将列表中的每个元素重复 k 次,我们将首先使用itertools.repeat()方法和list()构造函数为现有列表中的每个元素创建一个列表。这里,每个迭代器将有 k 次不同的元素。之后,我们将使用itertools.chain.from_iterable() 方法从使用itertools.repeat()方法创建的列表中创建输出列表。这样,我们将得到一个所有元素重复 k 次的列表。
import itertools
myList = [1, 2, 3, 4, 5]
print("The original list is:", myList)
k = 2
listOfLists = [list(itertools.repeat(element, k)) for element in myList]
newList = list(itertools.chain.from_iterable(listOfLists))
print("The output list is:", newList)
输出:
The original list is: [1, 2, 3, 4, 5]
The output list is: [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
结论
在本文中,我们讨论了 python 中列表中每个元素重复 k 次的三种方法。要阅读更多关于 python 中列表的内容,你可以阅读这篇关于如何用 python 从列表中删除最后一个元素的文章。
Python 中列表的重复元素
原文:https://www.pythonforbeginners.com/lists/repeat-elements-of-a-list-in-python
python 中的列表是最常用的数据结构之一。我们已经讨论了列表上的各种操作,比如计算列表中元素的频率或者反转列表。在本文中,我们将研究在 python 中重复列表元素的不同方法。
如何在 Python 中重复列表元素
为了在 python 中重复列表中的元素,我们将列表中现有的元素插入到同一个列表中。这样,列表中的元素就会重复出现。
例如,如果我们有一个列表myList=[1,2,3,4,5],我们必须重复列表的元素两次,输出列表将变成[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]。
在 python 中,我们可以使用 append()方法、extend()方法或*操作符来重复列表中的元素。我们将在下面的章节中详细讨论所有这些方法。
使用 append()方法重复列表中的元素
append()方法用于将元素追加到列表的最后。在列表上调用时,append()方法获取一个元素并将其添加到列表中,如下所示。
myList = [1, 2, 3, 4, 5]
print("The given list is:", myList)
number = 10
print("The input number to append to list is:", number)
myList.append(number)
print("The output list is:", myList)
输出:
The given list is: [1, 2, 3, 4, 5]
The input number to append to list is: 10
The output list is: [1, 2, 3, 4, 5, 10]
为了将列表中的元素重复 n 次,我们首先将现有的列表复制到一个临时列表中。之后,我们将使用 for 循环、range()方法和 append()方法将临时列表的元素添加到原始列表中 n 次。执行 for 循环后,列表中的元素将重复 n 次,如下例所示。
myList = [1, 2, 3, 4, 5]
print("The given list is:", myList)
tempList = list(myList)
count = 2
print("Number of Times to repeat the elements:",count)
for i in range(count):
for element in tempList:
myList.append(element)
print("The output list is:", myList)
输出:
The given list is: [1, 2, 3, 4, 5]
Number of Times to repeat the elements: 2
The output list is: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
使用 extend()方法重复列表中的元素
我们可以使用 extend()方法一次添加列表中的所有元素,而不是使用 append()方法逐个添加元素。在列表上调用 extend()方法时,它接受列表作为输入参数,并将输入列表添加到现有列表中,如下所示。
myList = [1, 2, 3, 4, 5]
print("The given list is:", myList)
newList = [6, 7]
print("The input list to append elements from is:", newList)
myList.extend(newList)
print("The output list is:", myList)
输出:
The given list is: [1, 2, 3, 4, 5]
The input list to append elements from is: [6, 7]
The output list is: [1, 2, 3, 4, 5, 6, 7]
要使用 extend()方法重复一个列表的元素,我们将把现有列表的元素复制到一个临时列表中。之后,我们将使用带有 for 循环的 extend()方法来重复列表中的元素,如下所示。
myList = [1, 2, 3, 4, 5]
print("The given list is:", myList)
tempList = list(myList)
count = 2
print("Number of Times to repeat the elements:",count)
for i in range(count):
myList.extend(tempList)
print("The output list is:", myList)
输出:
The given list is: [1, 2, 3, 4, 5]
Number of Times to repeat the elements: 2
The output list is: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
使用*运算符
运算符也可以用来重复列表中的元素。当我们使用*运算符将一个列表与任意数字相乘时,它会重复给定列表中的元素。这里,我们只需要记住,要重复元素 n 次,我们必须将列表乘以(n+1)。
myList = [1, 2, 3, 4, 5]
print("The given list is:", myList)
count = 2
print("Number of Times to repeat the elements:", count)
myList = myList * 3
print("The output list is:", myList)
输出:
The given list is: [1, 2, 3, 4, 5]
Number of Times to repeat the elements: 2
The output list is: [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
结论
在本文中,我们讨论了在 python 中重复列表元素的三种方法。在所有这些方法中,使用*操作符的方法是最有效和最容易实现的。因此,我建议您使用这种方法来重复 python 中的列表元素。要了解更多关于 python 中的列表,你可以阅读这篇关于 python 中的列表理解的文章。
在 Python 中替换字符串中的字符
原文:https://www.pythonforbeginners.com/basics/replace-characters-in-a-string-in-python
在程序中处理文本数据时,有时我们可能需要修改数据。在本文中,我们将看看在 Python 中替换字符串中的字符的各种方法。我们将讨论各种用例,以便更好地理解这个过程。
如何替换字符串中的一个字符?
要用另一个字符替换字符串中的一个字符,我们可以使用 replace()方法。在字符串上调用 replace()方法时,将被替换的字符作为第一个输入,新字符作为第二个输入,将被替换的字符数作为可选输入。replace()方法的语法如下:
str.replace(old_character, new_character, n)
这里,old_character 是将用 new_character 替换的字符。输入 n 是可选参数,指定必须用 new_character 替换的 old_character 的出现次数。
现在让我们讨论如何使用各种用例替换字符串中的字符。
替换字符串中出现的所有字符
要用新字符替换所有出现的字符,我们只需在字符串上调用 replace()方法时,将旧字符和新字符作为输入传递给该方法。您可以在下面的示例中观察到这一点。
input_string = "This is PythonForBeginners.com. Here, you can read python tutorials for free."
new_string = input_string.replace('i', "I")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
输出:
The original string is:
This is PythonForBeginners.com. Here, you can read python tutorials for free.
Output String is:
ThIs Is PythonForBegInners.com. Here, you can read python tutorIals for free.
这里,我们使用 replace()方法将所有出现的字符“I”替换为字符“I”。
我们也可以用一组新的字符替换一组连续的字符,而不是替换单个字符。替换连续字符组的语法保持不变。我们只需将旧字符和新字符传递给 replace()方法,如下所示。
input_string = "This is PythonForBeginners.com. Here, you can read python tutorials for free."
new_string = input_string.replace('is', "IS")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
输出:
The original string is:
This is PythonForBeginners.com. Here, you can read python tutorials for free.
Output String is:
ThIS IS PythonForBeginners.com. Here, you can read python tutorials for free.
在本例中,您可以看到我们在输出字符串中用“is”替换了“is”。
替换字符串中第 n 个出现的字符
要用另一个字符替换字符串中出现的前 n 个字符,我们可以在 replace()方法中指定可选的输入参数。指定要替换的字符的出现次数后,从字符串开始的 n 个字符将被替换。
例如,我们可以用“A”替换给定文本中出现的前 3 个字符“A ”,如下所示。
input_string = "An owl sat on the back of an elephant and started to tease him."
new_string = input_string.replace('a', "A",3)
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
输出:
The original string is:
An owl sat on the back of an elephant and started to tease him.
Output String is:
An owl sAt on the bAck of An elephant and started to tease him.
使用 replace()方法的好处
一般情况下,我们需要使用正则表达式来查找字符串中的字符,以替换它们。正则表达式很难理解,需要小心使用以匹配要正确替换的字符。此外,使用正则表达式在计算上也是低效的。因此,replace()方法为我们提供了一种简单且计算高效的方法来替换字符串中的字符。
结论
在本文中,我们讨论了 Python 中的 replace()方法。我们还看到了用它来处理文本或原始数据的各种方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 中的请求
原文:https://www.pythonforbeginners.com/requests/requests-in-python
什么是请求
Requests 模块是 Python 的一个优雅而简单的 HTTP 库。
我能对请求做什么?
请求允许您发送 HTTP/1.1 请求。
您可以使用简单的 Python 字典添加头、表单数据、多部分文件和参数,并以相同的方式访问响应数据。
注意,本帖笔记摘自 Python-Requests.org:http://docs.python-requests.org/en/latest/
请求安装
要安装请求,只需:
$ pip 安装请求
或者,如果你绝对必须:
$ easy_install 请求
请求
首先通过导入请求模块:
导入请求
现在,让我们试着得到一个网页。
对于这个例子,让我们获取 GitHub 的公开时间表
>>> r = requests.get('https://github.com/timeline.json')
现在,我们有一个名为 r 的响应对象,我们可以从这个对象中获得我们需要的所有信息。
要发出 HTTP POST 请求
>>> r = requests.post("http://httpbin.org/post")
You can also use other HTTP request types, like PUT, DELETE, HEAD and OPTIONS
>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options("http://httpbin.org/get")
响应内容
我们可以读取服务器响应的内容。
再次考虑 GitHub 时间轴:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.text
'[{"repository":{"open_issues":0,"url":"https://github.com/...
请求将自动解码来自服务器的内容。
大多数 unicode 字符集都可以无缝解码。
当您发出请求时,Requests 会根据 HTTP 头对响应的编码进行有根据的猜测。
当您访问 r.text 时,将使用请求猜测的文本编码。
您可以使用
r.encoding 属性找出正在使用的编码请求,并对其进行更改:
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
如果您更改编码,每当您调用 r.text 时,请求将使用 r.encoding 的新值
。
二元响应内容
对于非文本请求,还可以以字节形式访问响应正文:
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
JSON 响应内容
如果您正在处理 JSON 数据,还有一个内置的 JSON 解码器:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
如果 JSON 解码失败,r.json 只返回 None。
自定义标题
如果您想在请求中添加 HTTP 头,只需向 headers 参数传递一个 dict。
例如,在前面的示例中,我们没有指定内容类型:
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)
响应状态代码
我们可以检查响应状态代码:
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
# Requests also comes with a built-in status code lookup object for easy reference:
>>> r.status_code == requests.codes.ok
True
# If we made a bad request (non-200 response),
# we can raise it with Response.raise_for_status():
>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404
响应标题
我们可以使用 Python 字典查看服务器的响应头:
>>> r.headers
{
'status': '200 OK',
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json; charset=utf-8'
}
HTTP 头是不区分大小写的,所以我们可以使用我们想要的任何
大写来访问头:
>>> r.headers['Content-Type']
'application/json; charset=utf-8'
>>> r.headers.get('content-type')
'application/json; charset=utf-8'
# If a header doesn’t exist in the Response, its value defaults to None:
>>> r.headers['X-Random']
None
饼干
如果响应包含一些 Cookies,您可以快速访问它们:
>>> url = 'http://httpbin.org/cookies/set/requests-is/awesome'
>>> r = requests.get(url)
>>> r.cookies['requests-is']
'awesome'
# To send your own cookies to the server, you can use the cookies parameter:
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
基本认证
许多 web 服务需要身份验证。
有许多不同类型的认证,但最常见的是 HTTP
基本认证。
使用基本身份验证发出请求非常简单:
from requests.auth import HTTPBasicAuth
requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
# Due to the prevalence of HTTP Basic Auth,
# requests provides a shorthand for this authentication method:
requests.get('https://api.github.com/user', auth=('user', 'pass'))
以这种方式提供元组形式的凭证在功能上等同于上面的
HTTPBasicAuth 示例。
摘要认证
# Another popular form of web service protection is Digest Authentication:
>>> from requests.auth import HTTPDigestAuth
>>> url = 'http://httpbin.org/digest-auth/auth/user/pass'
>>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
重定向和历史记录
当使用 GET
和 OPTIONS 动词时,请求将自动执行位置重定向。
GitHub 将所有 HTTP 请求重定向到 HTTPS。
我们可以使用响应对象的历史方法来跟踪重定向。
让我们看看 Github 做了什么:
>>> import requests
>>> r = requests.get("http://github.com")
>>> r.url
u'https://github.com/'
>>> r.status_code
200
>>> r.history
[]
>>>
Response.history 列表包含为完成请求而创建的请求对象列表。
该列表从最早的请求到最近的请求进行排序。
如果使用 GET 或 OPTIONS,可以用
allow_redirects 参数禁用重定向处理:
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
超时设定
您可以使用 timeout 参数告诉请求在给定的
秒后停止等待响应:
>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
File "", line 1, in
requests.exceptions.Timeout: Request timed out.
错误和异常
如果出现网络问题(例如 DNS 故障、拒绝连接等),
请求将引发 ConnectionError 异常。
在罕见的无效 HTTP 响应事件中,
请求将引发一个 HTTPError 异常。
如果请求超时,将引发超时异常。
如果请求超过了配置的最大重定向数,就会引发 TooManyRedirects 异常。
请求显式引发的所有异常都继承自
Requests . exceptions . request exception。
您可以参考配置 API 文档,通过 danger_mode 选项立即引发
HTTPError 异常,或者让请求
捕获大多数 requests.exceptions
带有 safe_mode 选项的 RequestException 异常。
在 Python 中重置熊猫系列的索引
原文:https://www.pythonforbeginners.com/basics/reset-index-in-a-pandas-series-in-python
Pandas 系列对象在 python 中用于处理顺序数据。为了处理一个序列中的数据,我们通常使用元素的索引。在本文中,我们将讨论如何在熊猫系列中建立索引。
如何重置熊猫系列的索引?
为了重置熊猫系列的索引,我们可以使用两种方法。首先,我们可以将包含新索引的列表直接分配给 series 对象的index属性。或者,我们可以使用reset_index() 方法。让我们讨论这两种方法。
使用 Index 属性重置序列中的索引
index属性存储熊猫系列的索引。为了重置一个系列对象的索引,我们将首先使用len()函数找到系列对象的长度。len()函数将一个 iterable 对象作为其输入参数,并返回长度。
找到序列的长度后,我们将使用range()函数创建一个 range 对象,包含从 0 到序列长度的数字。range()函数将范围内的最大值作为其输入参数,并返回一个从 0 到(最大值-1)的范围对象。最后,我们将把 range 对象分配给系列的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 original series is:")
print(series)
lenSeries=len(series)
indices=range(lenSeries)
series.index=indices
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
0 a
1 b
2 c
3 ab
4 abc
5 abcd
6 bc
7 d
dtype: object
在上面的例子中,您可以观察到原始数据帧中的索引已经被移除,并且从 0 到 7 的新索引已经被分配给元素。
在上述方法中,您需要确保分配给序列的索引属性的 python 列表的长度必须等于序列中元素的数量。否则,程序将会遇到 ValueError 异常。
我们可以使用reset_index()方法来重置熊猫系列的索引,而不是使用index属性。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇 MLFlow 教程,里面有代码示例。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
reset index()方法
reset_index()方法的语法如下。
Series.reset_index(level=None, *, drop=False, name=_NoDefault.no_default, inplace=False, allow_duplicates=False)
这里,
level参数用于选择多级索引时需要删除的索引级别。您可以将需要从序列中删除的索引的级别、级别列表、索引名称或索引名称列表传递给level参数。- 默认情况下,当我们使用
reset_index()方法重置一个系列的索引时,该索引被添加为一个额外的列,并且我们从reset_index()方法得到一个 dataframe 作为输出,而不是一个系列。如果您想删除索引而不是将其转换为列,可以将drop参数设置为 True。 - 如果您想在
reset_index()方法的输出中使用原始序列的索引作为新列,您可以使用 name 参数来设置包含数据值的列的名称。默认情况下,包含索引值的列的名称被设置为“index”。在drop参数设置为真的情况下,name参数将被忽略。 - 默认情况下,
reset_index()方法在重置索引后返回一个新的序列。要修改原始序列,您可以将inplace参数设置为True。 allow_duplicates参数用于决定系列中是否允许重复的列标签。要重置系列的索引,allow_duplicates参数没有用。
使用 reset_index()方法重置序列中的索引
要重置序列中的索引,只需调用 series 对象上的reset_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 original series is:")
print(series)
series=series.reset_index()
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
index 0
0 3 a
1 23 b
2 11 c
3 14 ab
4 16 abc
5 2 abcd
6 45 bc
7 65 d
您可以观察到reset_index() 方法返回了一个 dataframe。reset_index() 方法将当前索引提升为一列,并返回一个熊猫数据帧而不是一个序列。
这里,包含数据值的列的名称被设置为 0。您可以使用reset_index()方法中的 name 参数设置数据列的名称,如下例所示。
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 original series is:")
print(series)
series=series.reset_index(name="letters")
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
index letters
0 3 a
1 23 b
2 11 c
3 14 ab
4 16 abc
5 2 abcd
6 45 bc
7 65 d
在上面的例子中,我们将文字"letters"传递给了reset_index()方法中的 name 参数。因此,当执行reset_index()方法时,它返回一个包含两列的数据帧,即 index 和 letters。这里,"index"是根据序列的原始索引创建的列的名称。然而,"letters"是序列中包含数据的列的名称。
如果您不想在重置索引时创建 dataframe 并删除索引列,您可以将reset_index()方法中的drop参数设置为 True,如下所示。
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 original series is:")
print(series)
series=series.reset_index(drop=True)
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
0 a
1 b
2 c
3 ab
4 abc
5 abcd
6 bc
7 d
dtype: object
在上面的例子中,我们已经将drop参数设置为 True。因此,reset_index()方法返回一个序列而不是一个数据帧。
使用 reset_index()方法就地重置索引
默认情况下,rest_index() 方法返回一个新的序列。如果要重置原始序列中的索引,可以将inplace参数设置为 True,如下所示。
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 original series is:")
print(series)
series.reset_index(drop=True,inplace=True)
print("The modified series is:")
print(series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The modified series is:
0 a
1 b
2 c
3 ab
4 abc
5 abcd
6 bc
7 d
dtype: object
在这个例子中,我们已经在reset_index() 方法中将inplace参数设置为 True。因此,这些指数将从原始序列中删除,而不是创建一个新的序列。在这种情况下,reset_index()方法在执行后返回 None。
结论
在本文中,我们讨论了在熊猫系列中重置索引的不同方法。要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
在 Python 中反转字典
原文:https://www.pythonforbeginners.com/basics/reverse-a-dictionary-in-python
python 中的字典是存储键值映射的好工具。在本文中,我们将讨论如何在 python 中反转字典。我们将使用不同的例子来做这件事,这样我们可以更好地理解这些方法。
如何用 Python 逆向一个字典?
当我们反转一个给定的 python 字典时,我们改变了键值对中值的顺序。在每个键-值对中,当前键成为值,当前值成为新字典中的键。例如,看看下面的字典。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
我们把这本字典翻过来之后,它会是这样的。
reversedDict = {1: 1, 4: 2, 9: 3, 16: 4, 25: 5}
在 python 中反转一个字典,我们可以使用 for 循环或者字典理解。让我们逐一讨论这两种方法。
使用 For 循环反转 Python 中的字典
要使用 for 循环反转字典,我们将首先创建一个空字典来存储反转的键-值对。之后,我们将遍历输入字典中的每个键值对。在遍历时,我们将使输入字典中的每个值成为输出字典中的一个键,与输入字典中的值相关联的键将成为输出字典中的关联值,如下所示。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
reversedDict = dict()
for key in myDict:
val = myDict[key]
reversedDict[val] = key
print("The reversed dictionary is:")
print(reversedDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The reversed dictionary is:
{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}
使用 keys()和 values()方法
您还可以使用带有 for 循环的keys() 和values() 方法来反转字典。在这种方法中,我们将首先创建一个键列表和一个输入字典的值列表。之后,我们将使值列表中的每个元素成为输出字典中的一个键。键列表中的关联元素将成为输出字典中的相应值,如下所示。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
reversedDict = dict()
key_list = list(myDict.keys())
val_list = list(myDict.values())
n = len(key_list)
for i in range(n):
key = val_list[i]
val = key_list[i]
reversedDict[key] = val
print("The reversed dictionary is:")
print(reversedDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The reversed dictionary is:
{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}
使用 items()方法
你也可以使用items() 方法来反转一个字典。在这种方法中,我们将从输入字典中逐个取出每个条目。之后,我们将如下反转键-值对。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
reversedDict = dict()
for item in myDict.items():
key = item[1]
val = item[0]
reversedDict[key] = val
print("The reversed dictionary is:")
print(reversedDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The reversed dictionary is:
{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}
使用字典理解
不使用 for 循环,我们可以使用 dictionary comprehension 在一条 python 语句中反转一个字典。这里,我们将通过反转字典的每个键-值对中的键和值来创建输出字典,如下所示。
myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print("The input dictionary is:")
print(myDict)
reversedDict = {val: key for (key, val) in myDict.items()}
print("The reversed dictionary is:")
print(reversedDict)
输出:
The input dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
The reversed dictionary is:
{1: 1, 4: 2, 9: 3, 16: 4, 25: 5}
结论
在本文中,我们讨论了用 python 反转字典的四种方法。要了解更多关于 python 中的字典,您可以阅读这篇关于如何将字典转换成元组列表的文章。你可能也会喜欢这篇关于用 python 理解列表的文章。
反转列表和字符串
原文:https://www.pythonforbeginners.com/code-snippets-source-code/reverse-loop-on-a-list
这篇短文将展示如何在 Python 中进行反向循环。
第一个例子将展示如何在一个列表中这样做,另一个例子将展示如何反转一个字符串。
只需打开一个 Python 解释器并进行测试。
创建一个包含一些值的列表,如下所示:
L1 = ["One", "two", "three", "four", "five"]
#To print the list as it is, simply do:
print L1
#To print a reverse list, do:
for i in L1[::-1]:
print i
>>Output:
five
four
three
two
One
我们也可以反转字符串,就像这样:
string = "Hello World"
print ' '.join(reversed(string))
>>Output:
d l r o W o l l e H
相关帖子:
Python 中的右连接数据帧
原文:https://www.pythonforbeginners.com/basics/right-join-dataframes-in-python
右连接操作用于连接 SQL 中的两个表。在本文中,我们将讨论如何在 python 中对两个数据帧执行正确的连接操作。
什么是正确的连接操作?
考虑两个表 A 和 B,其中 A 包含一个班级中学生的详细信息,而表 B 包含学生的分数。表 A 和表 B 都有一个公共列“Name”。当我们对表执行(A right join B)操作时,我们得到一个包含表 B 中所有行以及表 A 中相应行的表。除此之外,表 B 中与表 A 中没有任何匹配行的所有行也包含在输出表中。但是,属于表 A 的行,在表 B 中没有任何匹配的行,将从最终结果中忽略。
因此,我们将获得一个新表,其中包含个人详细信息以及表 b 中给出分数的学生的分数。输出表还将包含表 a 中未给出详细信息的学生的分数。但是,输出将不包含表 b 中未给出分数的学生的详细信息。
我们还可以对 pandas 数据帧执行右连接操作,因为数据帧包含表格形式的数据。为此,我们可以使用本文中讨论的merge()方法和join()方法。
您可以使用以下链接下载程序中使用的文件。
使用 Python 中的 merge()方法右连接数据帧
我们可以使用 python 中的merge()方法对数据帧执行正确的连接操作。为此,我们将在第一个数据帧上调用merge()方法。此外,我们将把第二个数据帧作为第一个输入参数传递给merge()方法。此外,我们将要匹配的列的名称作为输入参数传递给‘on’参数,并将文字‘right’作为输入参数传递给‘how’参数。执行后,merge() 方法将返回输出数据帧,如下例所示。
import pandas as pd
import numpy as np
names=pd.read_csv("name.csv")
grades=pd.read_csv("grade.csv")
resultdf=names.merge(grades,how="right",on="Name")
print("The resultant dataframe is:")
print(resultdf)
输出:
The resultant dataframe is:
Class_x Roll_x Name Class_y Roll_y Grade
0 1.0 11.0 Aditya 1 11 A
1 1.0 12.0 Chris 1 12 A+
2 2.0 1.0 Joel 2 1 B
3 2.0 22.0 Tom 2 22 B+
4 3.0 33.0 Tina 3 33 A-
5 3.0 34.0 Amy 3 34 A
6 NaN NaN Radheshyam 3 23 B+
7 NaN NaN Bobby 3 11 D
如果第一个数据帧中的行在第二个数据帧中没有匹配的数据帧,则这些行不会包含在输出中。然而,对于在第一数据帧中没有任何匹配行的第二数据帧中的行来说,情况并非如此。第二个数据帧的所有行都将包括在输出中,即使它们在第一个数据帧中没有任何匹配的行。您可以在下面的示例中观察到这一点。
如果两个数据帧中有同名的列,python 解释器会在列名中添加 _x 和_y后缀。为了识别数据帧中调用了merge()方法的列,添加了_x后缀。对于作为输入参数传递给merge() 方法的 dataframe,使用了_y后缀。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
使用 Python 中的 Join()方法右连接数据帧
不使用merge()方法,我们可以使用join() 方法在给定的数据帧上执行正确的连接操作。当在一个数据帧上调用 join() 方法时,它将另一个数据帧作为它的第一个输入参数。此外,我们将把要匹配的列的名称作为输入参数传递给‘on’参数,把文字“right”作为输入参数传递给'how'参数。执行后,join() 方法返回输出数据帧,如下例所示。
import pandas as pd
import numpy as np
names=pd.read_csv("name.csv")
grades=pd.read_csv("grade.csv")
grades=grades.set_index("Name")
resultdf=names.join(grades,how="right",on="Name",lsuffix='_names', rsuffix='_grades')
print("The resultant dataframe is:")
print(resultdf)
输出:
The resultant dataframe is:
Class_names Roll_names Name Class_grades Roll_grades Grade
0.0 1.0 11.0 Aditya 1 11 A
1.0 1.0 12.0 Chris 1 12 A+
3.0 2.0 1.0 Joel 2 1 B
4.0 2.0 22.0 Tom 2 22 B+
6.0 3.0 33.0 Tina 3 33 A-
7.0 3.0 34.0 Amy 3 34 A
NaN NaN NaN Radheshyam 3 23 B+
NaN NaN NaN Bobby 3 11 D
在使用join()方法时,您需要记住,要执行连接操作的列应该是作为输入参数传递给join()方法的 dataframe 的索引。如果数据帧的某些列有相同的列名,您需要使用lsuffix和rsuffix参数指定列名的后缀。如果列名相同,传递给这些参数的值可以帮助我们识别哪个列来自哪个数据帧。
结论
在本文中,我们讨论了在 python 中对数据帧执行正确连接操作的两种方法。想了解更多关于 python 编程的知识,可以阅读这篇关于字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
用 Python 将 Numpy 数组保存到文本文件
原文:https://www.pythonforbeginners.com/basics/save-numpy-array-to-text-file-in-python
python 中的数据分析广泛使用 Numpy 数组。在本文中,我们将讨论如何在 python 中将 numpy 数组保存到文本文件中。
使用 str()函数将 Numpy 数组保存到文本文件中
我们可以使用str()函数和文件处理将 numpy 数组保存到文本文件中。在这种方法中,我们将首先使用str()函数将 numpy 数组转换成一个字符串。str() 函数将 numpy 数组作为输入参数,并返回它的字符串表示。将 numpy 数组转换成字符串后,我们将把字符串保存到一个文本文件中。
为了将 numpy 数组保存到一个文本文件中,我们将首先使用open() 函数在 append 模式下打开一个文件。open()函数将文件名作为第一个输入参数,将文字“a”作为第二个输入参数,以表示文件是以追加模式打开的。执行后,它返回一个包含文本文件的 file 对象。
获得 file 对象后,我们将使用write()方法将包含 numpy 数组的字符串保存到文件中。在 file 对象上调用write()方法时,该方法将字符串作为其输入参数,并将该字符串追加到文件中。将字符串写入文件后,不要忘记使用close()方法关闭文件。
使用 str()函数将 numpy 数组保存到文本文件的完整代码如下。
import numpy as np
myFile = open('sample.txt', 'r+')
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The array is:", myArray)
print("The content of the file before saving the array is:")
text = myFile.read()
print(text)
myFile.write(str(myArray))
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the array is:")
text = myFile.read()
print(text)
输出:
The array is: [1 2 3 4 5 6 7 8 9]
The content of the file before saving the array is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
The content of the file after saving the array is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
[1 2 3 4 5 6 7 8 9]
推荐机器学习文章:机器学习中的回归与实例
使用 numpy.savetxt()函数将 Numpy 数组保存到文本文件中
不使用str()函数,我们可以使用numpy.savetxt()函数将 numpy 数组保存到 python 中的文本文件中。在这种方法中,我们首先使用前面例子中讨论的open()函数在追加模式下打开文本文件。打开文件后,我们将使用 numpy.savetxt()函数将数组保存到文本文件中。这里,numpy.savetxt()函数将 file 对象作为它的第一个输入参数,将 numpy 数组作为它的第二个输入参数。执行后,它将 numpy 数组保存到文本文件中。您可以在下面的示例中观察到这一点。
import numpy as np
myFile = open('sample.txt', 'r+')
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The array is:", myArray)
np.savetxt(myFile, myArray)
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the array is:")
text = myFile.read()
print(text)
输出:
The array is: [1 2 3 4 5 6 7 8 9]
The content of the file after saving the array is:
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
4.000000000000000000e+00
5.000000000000000000e+00
6.000000000000000000e+00
7.000000000000000000e+00
8.000000000000000000e+00
9.000000000000000000e+00
在执行savetxt()函数后,必须使用close() 对象关闭文件对象。否则,更改将不会写入文件。
结论
在本文中,我们讨论了用 python 将 numpy 数组保存到文本文件的两种方法。想了解更多关于 Python 编程的知识,可以阅读这篇关于 Python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
用 Python 抓取网站
原文:https://www.pythonforbeginners.com/beautifulsoup/scraping-websites-with-beautifulsoup
什么是 BeautifulSoup?
BeautifulSoup 是来自 Crummy 的第三方 Python 库。
该库是为像屏幕抓取这样的快速周转项目而设计的
我能做什么
Beautiful Soup 解析你给它的任何东西,并为你遍历树。
你可以用它来查找一个网站的所有链接
查找所有 URL 与“foo.com”匹配的链接
找到有粗体文本的表格标题,然后给我那个文本。
找到每一个有 href 属性的“a”元素。
我需要什么?
您需要首先安装 BeautifulSoup 模块,然后将
模块导入到您的脚本中。
可以用 pip install beautifulsoup4 或者 easy_install beautifulsoup4 安装。
在最近版本的 Debian 和 Ubuntu 中,它也可以作为 python-beautifulsoup4 包使用。
Beautiful Soup 4 在 Python 2 (2.6+)和 Python 3 上都可以工作。
美丽的例子
在开始之前,我们必须导入两个模块=> BeutifulSoup 和 urllib2
Urlib2 用来打开我们想要的 URL。
因为 BeautifulSoup 没有为您获取网页,所以您必须使用 urllib2 模块来完成这项工作。
#import the library used to query a website
import urllib2
搜索并查找所有 html 标签
我们将使用 soup.findAll 方法来搜索 soup 对象,以
匹配页面中的文本和 html 标签。
from BeautifulSoup import BeautifulSoup
import urllib2
url = urllib2.urlopen("http://www.python.org")
content = url.read()
soup = BeautifulSoup(content)
links = soup.findAll("a")
这将打印出 python.org 所有带有“a”标签的元素。
这是定义超链接的标签,用于从一个页面
链接到另一个页面
在 Reddit 上查找所有链接
使用 Python 内置的 urllib2 模块获取 Reddit 网页的 HTML。
一旦我们有了页面的实际 HTML,我们就创建一个新的 BeautifulSoup
类来利用它的简单 API。
from BeautifulSoup import BeautifulSoup
import urllib2
pageFile = urllib2.urlopen("http://www.reddit.com")
pageHtml = pageFile.read()
pageFile.close()
soup = BeautifulSoup("".join(pageHtml))
#sAll = soup.findAll("li")
sAll = soup.findAll("a")
for href in sAll:
print href
网站废了《赫芬顿邮报》
这是我在 newthinktank.com 看到的另一个例子
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re
# Copy all of the content from the provided web page
webpage = urlopen('http://feeds.huffingtonpost.com/huffingtonpost/LatestNews').read()
# Grab everything that lies between the title tags using a REGEX
patFinderTitle = re.compile('')
# Grab the link to the original article using a REGEX
patFinderLink = re.compile('')
# Store all of the titles and links found in 2 lists
findPatTitle = re.findall(patFinderTitle,webpage)
findPatLink = re.findall(patFinderLink,webpage)
# Create an iterator that will cycle through the first 16 articles and skip a few
listIterator = []
listIterator[:] = range(2,16)
soup2 = BeautifulSoup(webpage)
#print soup2.findAll("title")
titleSoup = soup2.findAll("title")
linkSoup = soup2.findAll("link")
for i in listIterator:
print titleSoup[i]
print linkSoup[i]
print "
"
更多阅读
http://www.crummy.com/software/BeautifulSoup/ http://www . new thinktank . com/2010/11/python-2-7-tutorial-pt-13-website-scraping/
http://kochi-coders.com/?p=122
刮痧地下
原文:https://www.pythonforbeginners.com/scraping/scraping-wunderground
概观
使用 API 既有趣又有教育意义。
谷歌、Reddit 和 Twitter 等许多公司向公众发布了它的 API,这样开发者就可以开发基于其服务的产品。
与 API 一起工作让你学会了引擎盖下的螺母和螺栓。
在这篇文章中,我们将研究地下天气 API。
地下天气
我们将建立一个应用程序,将连接到' Wunderground '和检索。
天气预报等。
Wunderground 提供全球各地的本地和长期天气预报、天气报告、
地图&热带天气状况。
应用程序接口
API 是一种协议,旨在被软件组件用作相互通信的接口。API 是一组编程指令和
标准,用于访问基于 web 的软件应用程序(如上所述)。
借助 API,应用程序可以在没有任何用户知识或
干预的情况下相互对话。
入门指南
当我们想要使用一个 API 时,我们需要做的第一件事是查看
公司是否提供任何 API 文档。既然我们想为
神童世界写一份申请,我们就去神童世界网站
在页面底部,您应该会看到“面向开发人员的天气 API”。
API 文档
大多数 API 特性都需要一个 API 密匙,所以在开始使用天气 API 之前,让我们先注册一个
密匙。
在文档中,我们还可以看到 API 请求是通过 HTTP
发出的,数据特性返回 JSON 或 XML。
要阅读完整的 API 文档,请参见此链接。
在获得密钥之前,我们需要先创建一个免费帐户。
API 密钥
下一步是注册 API 密匙。只需填写您的姓名、电子邮件地址、
项目名称和网站,您就可以开始了。
互联网上的许多服务(如 Twitter、脸书..)要求你
有一个“API 密匙”。
应用编程接口密钥(API key)是由调用 API 的
计算机程序传入的代码,用于向网站标识调用程序、其开发者、
或其用户。
API 密钥用于跟踪和控制 API 的使用方式,例如
防止恶意使用或滥用 API。
API 密钥通常既作为唯一的标识符,又作为用于
认证的秘密令牌,并且通常具有一组对与之相关联的 API
的访问权限。
美国城市的现状
Wunderground 在他们的 API 文档中为我们提供了一个例子。
美国城市的现状
http://api.wunderground.com/api/0def10027afaebb7/conditions/q/CA/San_Francisco.json
如果您点击“显示响应”按钮,或者将该 URL 复制并粘贴到您的
浏览器中,您应该会看到类似这样的内容:
{
"response": {
"version": "0.1"
,"termsofService": "http://www.wunderground.com/weather/api/d/terms.html"
,"features": {
"conditions": 1
}
}
, "current_observation": {
"image": {
"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title":"Weather Underground",
"link":"http://www.wunderground.com"
},
"display_location": {
"full":"San Francisco, CA",
"city":"San Francisco",
"state":"CA",
"state_name":"California",
"country":"US",
"country_iso3166":"US",
"zip":"94101",
"magic":"1",
"wmo":"99999",
"latitude":"37.77500916",
"longitude":"-122.41825867",
"elevation":"47.00000000"
},
.....
锡达拉皮兹的现状
在“代码示例”页面上,我们可以看到检索锡达拉皮兹
当前温度的完整 Python 代码。
复制并粘贴到你最喜欢的编辑器,并保存为任何你喜欢的。
请注意,您必须用自己的 API 密钥替换“0def10027afaebb7”。
import urllib2
import json
f = urllib2.urlopen('http://api.wunderground.com/api/0def10027afaebb7/geolookup/conditions/q/IA/Cedar_Rapids.json')
json_string = f.read()
parsed_json = json.loads(json_string)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print "Current temperature in %s is: %s" % (location, temp_f)
f.close()
要在终端中运行程序:
python get_current_temp.py
您的程序将返回锡达拉皮兹的当前温度:
锡达拉皮兹现在的温度是 68.9 度
下一步是什么?
既然我们已经查看并测试了 Wunderground 提供的示例,让我们自己创建一个程序。
地下天气为我们提供了一大堆
可以利用的数据特征。
重要的是,你要通读那里的信息,了解如何使用不同的功能。
标准请求 URL 格式
"大多数 API 特性都可以使用以下格式访问。
注意,几个特性可以组合成一个请求。"
http://api.wunderground.com/api/0def10027afaebb7/features/settings/q/query.format
其中:
0def10027afaebb7: 您的 API 密钥
特性:以下一个或多个数据特性
设置(可选):示例:lang:FR/pws:0
查询:您想要获取天气信息的位置
格式: json,或 xml
我想做的是检索巴黎的天气预报。
预测功能返回未来 3 天的天气摘要。
这包括高温和低温,字符串文本预报和条件。
巴黎天气预报
要检索巴黎的天气预报,我首先要找到法国的国家代码,我可以在这里找到:
下一步是在 API 文档中寻找“特性:预测”。
我们需要的字符串可以在这里找到:
http://www.wunderground.com/weather/api/d/docs?d =数据/预测
通过阅读文档,我们应该能够构建一个 URL。
进行 API 调用
我们现在有了需要的 URL,可以开始我们的程序了。
现在是时候对 Weather Underground 进行 API 调用了。
注意:在这个程序中,我们将使用“请求”模块,而不是像我们在上面的例子中那样使用 urllib2 模块。
使用“请求”模块进行 API 调用非常容易。
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
现在,我们有一个名为“r”的响应对象。我们可以从这个物体中获得我们需要的所有信息。
创建我们的应用程序
打开您选择的编辑器,在第一行,导入请求模块。
注意,requests 模块带有一个内置的 JSON 解码器,我们可以对 JSON 数据使用
。这也意味着,我们不必导入 JSON
模块(就像我们在前面的例子中使用 urllib2 模块时所做的那样)
import requests
为了开始提取我们需要的信息,我们首先要看到“r”对象返回给我们什么键。
下面的代码将返回键,并应返回[u'response ',u'forecast']
import requests
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
data = r.json()
print data.keys()
获取我们想要的数据
将 URL(从上面)复制并粘贴到 JSON 编辑器中。
我使用http://jsoneditoronline.org/,但是任何 JSON 编辑器都应该做这项工作。
这将显示所有数据的更简单的概览。
http://API . wunderground . com/API/your _ API _ key/forecast/q/France/Paris . JSON
请注意,通过输入以下命令,可以通过终端获得相同的信息:
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
print r.text
检查给我们的输出后,我们可以看到我们感兴趣的数据在“forecast”键中。回到我们的程序,从那个键中打印出
数据。
import requests
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
data = r.json()
print data['forecast']
结果存储在变量“数据”中。
为了访问我们的 JSON 数据,我们简单地使用括号符号,就像这样:
data['key']。
让我们通过添加“简单预测”来浏览更多的数据
import requests
r = requests.get("http://api.wunderground.com/api/your_api_key/forecast/q/France/
Paris.json")
data = r.json()
print data['forecast']['simpleforecast']
我们的产出仍然有点多,但是坚持住,我们就快到了。
我们程序的最后一步是添加['forecastday'],而不是打印出每一个条目,我们将使用 for 循环来遍历字典。
我们可以像这样访问任何我们想要的东西,只要查找你感兴趣的数据。
在这个程序中,我想得到巴黎的天气预报。
让我们看看代码是什么样子的。
import requests
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/France/Paris.json")
data = r.json()
for day in data['forecast']['simpleforecast']['forecastday']:
print day['date']['weekday'] + ":"
print "Conditions: ", day['conditions']
print "High: ", day['high']['celsius'] + "C", "Low: ", day['low']['celsius'] + "C", '
'
运行程序。
$ python get_temp_paris.py
Monday:
Conditions: Partly Cloudy
High: 23C Low: 10C
Tuesday:
Conditions: Partly Cloudy
High: 23C Low: 10C
Wednesday:
Conditions: Partly Cloudy
High: 24C Low: 14C
Thursday:
Conditions: Mostly Cloudy
High: 26C Low: 15C
预测功能只是众多功能之一。剩下的我就交给你去探索了。
一旦你理解了一个 API 和它在 JSON 中的输出,你就明白了大多数 API 是如何工作的。
更多阅读
Python 代码:计算平均分
原文:https://www.pythonforbeginners.com/code-snippets-source-code/script-average-score
概观
This script will calculate the average of three values.
Make sure to put in "int" before the raw_input function, since we are
using integers.
# Get three test score
round1 = int(raw_input("Enter score for round 1: "))
round2 = int(raw_input("Enter score for round 2: "))
round3 = int(raw_input("Enter score for round 3: "))
# Calculate the average
average = (round1 + round2 + round3) / 3
# Print out the test score
print "the average score is: ", average
Happy Scripting
获取 IP 地址的地理位置
又到了脚本的时间了,这个脚本将根据用户的输入地理定位一个 IP 地址。对于这个脚本,我们将使用一组 Python 模块来完成这个任务。首先,我们检查用户是否输入了足够的参数,如果没有,他们的“用法”变量将被打印出来,告诉用户如何使用它。
我们使用 geody web 服务来查找 IP 的地理位置。
import re
import sys
import urllib2
import BeautifulSoup
usage = "Run the script: ./geolocate.py IPAddress"
if len(sys.argv)!=2:
print(usage)
sys.exit(0)
if len(sys.argv) > 1:
ipaddr = sys.argv[1]
geody = "http://www.geody.com/geoip.php?ip=" + ipaddr
html_page = urllib2.urlopen(geody).read()
soup = BeautifulSoup.BeautifulSoup(html_page)
# Filter paragraph containing geolocation info.
paragraph = soup('p')[3]
# Remove html tags using regex.
geo_txt = re.sub(r'<.*?>', '', str(paragraph))
print geo_txt[32:].strip()
这个脚本是从 snipplr.com 的这个帖子上复制的
脚本:从提示中获取用户名…
原文:https://www.pythonforbeginners.com/code-snippets-source-code/script-get-the-username-from-a-prompt
这个脚本将使用 raw_input 函数要求用户输入用户名。然后创建一个名为 user1 和 user2 的允许用户列表。控制语句检查来自用户的输入是否与允许用户列表中的输入相匹配。
#!/usr/bin/env python
#get the username from a prompt
username = raw_input("Login: >> ")
#list of allowed users
user1 = "Jack"
user2 = "Jill"
#control that the user belongs to the list of allowed users
if username == user1:
print "Access granted"
elif username == user2:
print "Welcome to the system"
else:
print "Access denied"
Python 密码生成器
原文:https://www.pythonforbeginners.com/code-snippets-source-code/script-password-generator
密码生成器
您可以使用 Pythons 字符串和随机模块来生成密码。
字符串模块包含了许多有用的常量和类。
其中一些我们将在这个脚本中使用。
string . ascii _ letters
ascii(大写和小写)字母的串联
string.digits
字符串‘0123456789’。
string.punctuation
在 C
语言环境中被视为标点符号的 ASCII 字符串。
打印字符串. ascii _ 字母
打印字符串.数字
打印字符串。标点符号
输出
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
!" #$% & '()*+,-。/:;< = > 【邮件保护】【]^_`{|}~】
密码生成器脚本
因此,为了将这些放在一起,我们可以使用一个非常好的密码生成器脚本。
import string
from random import *
characters = string.ascii_letters + string.punctuation + string.digits
password = "".join(choice(characters) for x in range(randint(8, 16)))
print password
更多阅读
更多脚本,请参见代码示例页面。
在 Python 中从列表中选择随机元素
原文:https://www.pythonforbeginners.com/basics/select-random-element-from-a-list-in-python
在用 python 编程时,我们可能需要在几种情况下从列表中选择一个随机元素。在本文中,我们将讨论在 python 中从列表中选择元素的不同方法。
使用随机模块从列表中选择随机元素
python 中的random模块为我们提供了不同的函数来生成随机数。我们也可以使用这个模块中定义的函数从列表中选择随机元素。
为了在 python 中从列表中选择一个随机元素,我们可以使用在random模块中定义的choice()函数。choice()函数将一个列表作为输入,并在每次执行时从列表中返回一个随机元素。
您可以在下面的示例中观察到这一点。
import random
myList = [1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
print("The list is:")
print(myList)
random_element = random.choice(myList)
print("The randomly selected element is:", random_element)
输出:
The list is:
[1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
The randomly selected element is: 8
使用秘密模块从列表中选择随机元素
secrets模块用于生成适用于管理数据(如密码、帐户认证、安全令牌和相关机密)的加密强随机数。然而,我们也可以使用这个模块从列表中选择一个随机元素。
secrets 模块中定义的choice()函数与 random 模块中定义的choice()函数工作方式相同。它接受一个列表作为输入,并从列表中返回一个元素,如下所示。
import secrets
myList = [1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
print("The list is:")
print(myList)
random_element = secrets.choice(myList)
print("The randomly selected element is:", random_element)
输出:
The list is:
[1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
The randomly selected element is: 45
使用 numpy 模块
我们也可以使用来自numpy模块的 choice()函数从列表中选择一个随机元素。numpy模块中的choice()功能与random模块或secrets模块的工作方式相同。您可以在下面的示例中观察到这一点。
import numpy
myList = [1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
print("The list is:")
print(myList)
random_element = numpy.random.choice(myList)
print("The randomly selected element is:", random_element)
输出:
The list is:
[1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
The randomly selected element is: 3
使用numpy模块时,我们有一个好处,我们甚至可以从列表中随机选择多个选项。为此,我们将使用函数的“size”参数。如果我们想从给定的列表中选择n随机元素,我们将把数字 n 作为第二个输入参数传递给在numpy模块中定义的choice()函数。执行后,该函数返回如下所示的 n元素列表。
import numpy
myList = [1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
print("The list is:")
print(myList)
random_elements = numpy.random.choice(myList, 4)
print("The randomly selected elements are:")
for x in random_elements:
print(x)
输出:
The list is:
[1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
The randomly selected elements are:
78
3
6
23
在这里,您可以观察到在输出列表中可以多次选择一个元素。为了避免这种情况,我们将使用第三个参数,即replace,并将其设置为False。在此之后,一旦选择了一个元素,就不会考虑对其进行另一次选择。因此,一个元素在输出列表中只会出现一次。您可以在下面的示例中观察到这一点。
import numpy
myList = [1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
print("The list is:")
print(myList)
random_elements = numpy.random.choice(myList, 4, replace=False)
print("The randomly selected elements are:")
for x in random_elements:
print(x)
输出:
The list is:
[1, 2, 3, 45, 6, 8, 78, 23, 56, 7686, 123]
The randomly selected elements are:
1
56
3
2
结论
在本文中,我们讨论了几种在 python 中从列表中选择随机元素的方法。我们还看到了如何从列表中选择多个随机元素。要了解更多关于 python 中的列表,你可以阅读这篇关于列表理解的文章。您可能也会喜欢这篇关于 python 中的字符串连接的文章。
用 Python 从数据帧中选择行
原文:https://www.pythonforbeginners.com/basics/select-row-from-a-dataframe-in-python
Pandas 数据帧用于在 Python 中处理表格数据。在本文中,我们将讨论如何用 Python 从数据帧中选择一行。我们还将讨论如何使用布尔运算符从 pandas 数据帧中选择数据。
使用 iloc 属性从数据帧中选择行
属性包含一个作为数据帧中行的有序集合的对象。iloc属性的功能类似于列表索引。您可以使用iloc属性从数据框中选择一行。为此,您可以简单地使用带有iloc属性的方括号内的行的位置来选择熊猫数据帧的一行,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
position=1
row=myDf.iloc[position]
print("The row at position {} is :{}".format(position,row))
输出:
The 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 row at position 1 is :Class 1
Roll 12
Name Chris
Name: 1, dtype: object
在这里,您可以观察到iloc属性将指定位置的行作为输出。
使用 Python 中的 loc 属性从数据帧中选择行
dataframe 的loc属性的工作方式类似于 python 字典的键。loc属性包含一个_LocIndexer对象,您可以用它从一个熊猫数据帧中选择行。您可以使用带有loc属性的方括号内的索引标签来访问熊猫系列的元素,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
index=2
row=myDf.loc[index]
print("The row at index {} is :{}".format(index,row))
输出:
The 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 row at index 2 is :Class 1
Roll 13
Name Sam
Name: 2, dtype: object
如果您已经为数据帧定义了一个自定义索引,您可以使用行的索引值从 pandas 数据帧中选择该行,如下所示。
myDf=pd.read_csv("samplefile.csv",index_col=0)
print("The dataframe is:")
print(myDf)
index=1
row=myDf.loc[index]
print("The row at index {} is :{}".format(index,row))
输出:
The dataframe is:
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
The row at index 1 is : Roll Name
Class
1 11 Aditya
1 12 Chris
1 13 Sam
如果有多级索引,可以使用这些索引从数据帧中选择行,如下所示。
myDf=pd.read_csv("samplefile.csv",index_col=[0,1])
print("The dataframe is:")
print(myDf)
index=(1,12)
row=myDf.loc[index]
print("The row at index {} is :{}".format(index,row))
输出:
The dataframe is:
Name
Class Roll
1 11 Aditya
12 Chris
13 Sam
2 1 Joel
22 Tom
44 Samantha
3 33 Tina
34 Amy
The row at index (1, 12) is :Name Chris
Name: (1, 12), dtype: object
在 Pandas 数据框架中使用列名选择列
要从数据帧中选择一列,可以使用带方括号的列名,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
column_name="Class"
column=myDf[column_name]
print("The {} column is :{}".format(column_name,column))
输出:
The 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 Class column is :0 1
1 1
2 1
3 2
4 2
5 2
6 3
7 3
Name: Class, dtype: int64
如果要从数据帧中选择多个列,可以将列名列表传递给方括号,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
column_names=["Class","Name"]
column=myDf[column_names]
print("The {} column is :{}".format(column_names,column))
输出:
The 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 ['Class', 'Name'] column is : Class Name
0 1 Aditya
1 1 Chris
2 1 Sam
3 2 Joel
4 2 Tom
5 2 Samantha
6 3 Tina
7 3 Amy
熊猫数据帧中的布尔屏蔽
布尔屏蔽用于检查数据帧中的条件。当我们在 dataframe 列上应用一个布尔操作符时,它根据如下所示的条件返回一个包含True和False值的 pandas 系列对象。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
boolean_mask=myDf["Class"]>1
print("The boolean mask is:")
print(boolean_mask)
输出:
The 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 boolean mask is:
0 False
1 False
2 False
3 True
4 True
5 True
6 True
7 True
Name: Class, dtype: bool
您可以使用布尔掩码从数据帧中选择行。为此,您需要将包含布尔掩码的序列传递给方括号运算符,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
boolean_mask=myDf["Class"]>1
print("The boolean mask is:")
print(boolean_mask)
print("The rows in which class>1 is:")
rows=myDf[boolean_mask]
print(rows)
输出:
The 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 boolean mask is:
0 False
1 False
2 False
3 True
4 True
5 True
6 True
7 True
Name: Class, dtype: bool
The rows in which class>1 is:
Class Roll Name
3 2 1 Joel
4 2 22 Tom
5 2 44 Samantha
6 3 33 Tina
7 3 34 Amy
除了使用方括号,您还可以使用where()方法通过布尔屏蔽从数据帧中选择行。在 dataframe 上调用where()方法时,该方法将布尔掩码作为其输入参数,并返回包含所需行的新 dataframe,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
boolean_mask=myDf["Class"]>1
print("The boolean mask is:")
print(boolean_mask)
print("The rows in which class>1 is:")
rows=myDf.where(boolean_mask)
print(rows)
输出:
The 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 boolean mask is:
0 False
1 False
2 False
3 True
4 True
5 True
6 True
7 True
Name: Class, dtype: bool
The rows in which class>1 is:
Class Roll Name
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 2.0 1.0 Joel
4 2.0 22.0 Tom
5 2.0 44.0 Samantha
6 3.0 33.0 Tina
7 3.0 34.0 Amy
在上面使用where()方法的例子中,布尔掩码的值为False、NaN的行存储在 dataframe 中。您可以删除包含NaN值的行,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
boolean_mask=myDf["Class"]>1
print("The boolean mask is:")
print(boolean_mask)
print("The rows in which class>1 is:")
rows=myDf.where(boolean_mask).dropna()
print(rows)
输出:
The 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 boolean mask is:
0 False
1 False
2 False
3 True
4 True
5 True
6 True
7 True
Name: Class, dtype: bool
The rows in which class>1 is:
Class Roll Name
3 2.0 1.0 Joel
4 2.0 22.0 Tom
5 2.0 44.0 Samantha
6 3.0 33.0 Tina
7 3.0 34.0 Amy
您还可以使用逻辑运算符从两个或多个条件创建布尔掩码,如下所示。
myDf=pd.read_csv("samplefile.csv")
print("The dataframe is:")
print(myDf)
boolean_mask=(myDf["Class"]>1) & (myDf["Class"]<3)
print("The boolean mask is:")
print(boolean_mask)
print("The rows in which class>1 and <3 is:")
rows=myDf.where(boolean_mask).dropna()
print(rows)
输出:
The 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 boolean mask is:
0 False
1 False
2 False
3 True
4 True
5 True
6 False
7 False
Name: Class, dtype: bool
The rows in which class>1 and <3 is:
Class Roll Name
3 2.0 1.0 Joel
4 2.0 22.0 Tom
5 2.0 44.0 Samantha
创建布尔掩码后,您可以使用它来选择布尔掩码包含 True 的行,如下所示。
结论
在本文中,我们讨论了如何从数据帧中选择一行。我们还讨论了如何从数据帧中选择一列,以及如何使用布尔掩码从数据帧中选择多行。
要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。如果你想进入机器学习领域,你可以阅读这篇关于机器学习中的回归的文章。
使用 Python 发送电子邮件
原文:https://www.pythonforbeginners.com/api/send-email-using-python
电子邮件是我们生活中最重要的部分之一。在本文中,我们将讨论如何使用 python 发送电子邮件。
如何使用 Python 发送电子邮件?
在本文中,我们将使用简单邮件传输协议(SMTP)通过 python 发送电子邮件。为此,我们将使用 smtplib 模块。此外,我们将使用 gmail.com 电子邮件 id 发送电子邮件。我们需要指定邮件平台,因为不同的邮件平台使用不同的端口号来发送电子邮件。因此,我们需要知道邮件服务提供商使用 python 发送电子邮件所使用的端口号。
建议阅读:用 Python 创建聊天应用
使用 Python 中的 smtplib 模块发送电子邮件的步骤
为了使用 smtplib 模块发送邮件,我们将遵循以下步骤。
- 首先,我们将使用 import 语句导入 smtplib 模块。
- 之后,我们将使用 SMTP()方法创建一个会话。SMTP()方法将邮件服务器位置作为第一个输入参数,将端口号作为第二个输入参数。这里,我们将传递“smtp.gmail.com”作为邮件服务器位置,传递 587 作为端口号。执行后,SMTP()方法创建一个 SMTP 会话。
- 我们将在 SMTP 会话中使用传输层安全性(TLS)。为此,我们将对 SMTP()方法返回的会话对象调用 starttls()方法。
- 启动 TLS 后,我们将登录我们的 Gmail 帐户。为此,我们将使用 login()方法。在会话对象上调用 login()方法时,它接受用户名作为第一个输入参数,接受密码作为第二个输入参数。如果用户名和密码正确,您将登录 Gmail。否则,程序将会出错。
- 登录后,我们将使用 sendmail()方法发送电子邮件。在会话对象上调用 sendmail()方法时,它将发送者的电子邮件地址作为第一个输入参数,接收者的电子邮件地址作为第二个输入参数,要发送的消息作为第三个输入参数。执行后,邮件会发送到收件人的电子邮件地址。
- 发送电子邮件后,我们将通过调用 session 对象上的 quit()方法来终止 SMTP 会话。
下面是使用 python 发送电子邮件的代码。
import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
email_id="[[email protected]](/cdn-cgi/l/email-protection)" #your email
password= "*********" password of gmail account
s.login("email_id", "password")
message= "Email Body"
s.sendmail("email_id", "receiver_email_id", message)
s.quit()
结论
在本文中,我们讨论了如何使用 python 发送电子邮件。要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
使用谷歌发送电子邮件
原文:https://www.pythonforbeginners.com/code-snippets-source-code/sending-emails-using-google
概观
系统管理员和开发人员的一项常见任务是在出现错误时使用脚本发送电子邮件。
为什么使用 Gmail?
使用谷歌的 SMTP 服务器可以免费使用,而且转发电子邮件的效果非常好。请注意,谷歌有一个发送限制:“如果你向超过 500 个收件人发送消息,或者如果你发送了大量无法送达的消息,谷歌将暂时禁用你的帐户。”只要你同意,你就可以走了。
我从哪里开始?
使用 SMTP(简单邮件传输协议)服务器通过 Python 的 smtplib 发送邮件。由于我们将使用谷歌的 SMTP 服务器来发送我们的电子邮件,我们将需要收集信息,如服务器,端口,认证。谷歌搜索很容易找到这些信息。
谷歌的标准配置说明
入门指南
首先打开您最喜欢的文本编辑器,并在脚本顶部导入 smtplib 模块。
import smtplib
已经在顶部,我们将创建一些 SMTP 头。
fromaddr = '[[email protected]](/cdn-cgi/l/email-protection)'
toaddrs = '[[email protected]](/cdn-cgi/l/email-protection)'
msg = 'Enter you message here’
完成后,创建一个 SMTP 对象,用于连接服务器。
server = smtplib.SMTP("smtp.gmail.com:587”)
接下来,我们将使用 Gmail 所需的 starttls()函数。
server.starttls()
接下来,登录到服务器:
server.login(username,password)
然后,我们将发送电子邮件:
server.sendmail(fromaddr, toaddrs, msg)
最终方案
你可以在下面看到完整的程序,现在你应该能理解它是干什么的了。
import smtplib
# Specifying the from and to addresses
fromaddr = '[[email protected]](/cdn-cgi/l/email-protection)'
toaddrs = '[[email protected]](/cdn-cgi/l/email-protection)'
# Writing the message (this message will appear in the email)
msg = 'Enter you message here'
# Gmail Login
username = 'username'
password = 'password'
# Sending the mail
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
更多阅读
Python 中的集合理解
原文:https://www.pythonforbeginners.com/basics/set-comprehension-in-python
在 python 编程中,我们使用不同的数据结构,如列表、元组、集合和字典。我们经常从程序中现有的对象创建新的列表、集合或字典。在本文中,我们将研究集合理解,并了解如何在 python 中使用它从 Python 中的现有对象创建新的集合。我们还将看一些 Python 中集合理解的例子。
Python 中的集合理解是什么?
集合理解是一种使用列表、集合或元组等其他可迭代元素在 python 中创建集合的方法。就像我们使用列表理解来创建列表一样,我们可以使用集合理解而不是 for 循环来创建一个新的集合并向其中添加元素。
Python 中集合理解的语法
集合理解的语法如下。
newSet= { 表达式为中的元素**可迭代 }**
语法描述:
- iterable 可以是 Python 中的任何 iterable 对象或数据结构,我们必须使用其中的元素来创建新的集合。
- 元素表示 iterable 中必须包含在集合中的元素。
- 表达式可以是从元素导出的任何数学表达式。
- 新集合是新集合的名称,它必须从可迭代的元素中创建。
让我们用一个例子来讨论这个语法。在下面的例子中,我们得到了一个由 10 个整数组成的列表。我们必须创建这些整数的三元组。这可以使用集合理解来完成,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
newSet = {element*3 for element in myList}
print("The existing list is:")
print(myList)
print("The Newly Created set is:")
print(newSet)
输出:
The existing list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The Newly Created set is:
{3, 6, 9, 12, 15, 18, 21, 24, 27, 30}
在上面的例子中,我们得到了一个由 10 个整数组成的列表,并且我们已经创建了一组由给定列表中的元素组成的三元组。在语句“newSet = { element * 3 for element in my list }”中,Set comprehension 用于创建包含三个一组的 myList 中的元素的。
如果您将代码与语法进行比较以理解集合,可以得出以下结论。
- mySet 是其元素已经被用来创建新集合的集合。因此 mySet 被用来代替 iterable。
- 我们已经创建了一个新的集合,它包含了我的列表中的三个元素。因此,**元素3** 被用来代替表达式。*
我们也可以在集合理解中使用条件句。在集合理解中使用条件语句的语法如下。
newSet= { 表达式 for 元素 in iterable if 条件 }
语法描述:
- iterable 可以是 Python 中的任何 iterable 对象或数据结构,我们必须使用其中的元素来创建新的集合。
- 条件是一个条件表达式,使用
- 元素表示 iterable 中必须包含在集合中的元素。
- 表达式可以是从元素*导出的任何数学表达式。*
- 新集合是新集合的名称,它必须从可迭代*的元素中创建。*
让我们用一个例子来讨论这个语法。在下面的例子中,我们得到了一个由 10 个整数组成的列表。我们必须创建一组偶数的三元组。这可以使用集合理解来完成,如下所示。
*`myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
newSet = {element*3 for element in myList if element % 2 ==0}
print("The existing list is:")
print(myList)
print("The Newly Created set is:")
print(newSet)`*
输出:
*`The existing list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The Newly Created set is:
{6, 12, 18, 24, 30}`*
在上面的例子中,我们有一个 10 个整数的列表,并且我们已经创建了一个给定列表中偶数元素的三元组。在语句“newSet = { element * 3 for element in my list if element % 2 = = 0 }”中,Set comprehension 用于创建包含 myList 中偶数元素的平方的 newSet 。
如果我们将代码与用于集合理解的语法进行比较,可以得出以下观察结果。
- myList 是其元素已被用于创建新集合的列表。因此我的列表被用来代替可重复。
- 我们必须创建一个新的列表,其中包含三个偶元素。因此,**元素3** 被用来代替表达式。*
- 为了只选择偶数元素,我们在条件处使用了条件语句“element % 2 == 0”。
集合理解的例子
现在我们已经理解了 python 中集合理解的语法,我们将通过一些例子来更好地理解这个概念。
从另一个集合的元素创建一个集合
如果必须使用另一个集合的元素创建一个集合,可以通过创建新的集合来实现。创建新集合后,可以使用 add()方法和 for 循环向新集合添加元素。在下面的例子中,我们创建了一个新的集合,它包含了一个现有集合的元素的平方。
*`mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = set()
for element in mySet:
newSet.add(element**2)
print("The existing set is:")
print(mySet)
print("The Newly Created set is:")
print(newSet)`*
输出:
*`The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The Newly Created set is:
{64, 1, 4, 36, 100, 9, 16, 49, 81, 25}`*
在上面的例子中,初始化一个空集,然后使用 add()方法向其中添加元素是低效的。取而代之的是,我们可以使用集合理解直接初始化包含所有元素的新集合,如下所示。
*`mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = {element ** 2 for element in mySet}
print("The existing set is:")
print(mySet)
print("The Newly Created set is:")
print(newSet)`*
输出:
*`The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The Newly Created set is:
{64, 1, 4, 36, 100, 9, 16, 49, 81, 25}`*
基于条件从集合中筛选元素
通过对元素应用一些条件,我们可以从旧集合的元素创建一个新集合。要使用 for 循环实现这一点,可以使用条件语句和 add()方法,如下所示。在下面的例子中,我们从一个集合中过滤了偶数。
*`mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = set()
for element in mySet:
if element % 2 == 0:
newSet.add(element)
print("The existing set is:")
print(mySet)
print("The Newly Created set is:")
print(newSet)`*
输出:
*`The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The Newly Created set is:
{2, 4, 6, 8, 10}`*
除了 for 循环,您还可以使用集合理解从旧集合中过滤出元素来创建一个新集合,如下所示。
*`mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = {element for element in mySet if element % 2 == 0}
print("The existing set is:")
print(mySet)
print("The Newly Created set is:")
print(newSet)`*
输出:
*`The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The Newly Created set is:
{2, 4, 6, 8, 10}`*
从集合中删除元素
如果您必须从集合中删除一些元素,您可以从尚未删除的元素创建一个新集合。之后,您可以将新集合分配给旧集合变量,如下所示。在下面的例子中,我们删除了集合中所有的奇数元素。
*`mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
print("The existing set is:")
print(mySet)
mySet = {element for element in mySet if element % 2 == 0}
print("The modified set is:")
print(mySet)`*
输出:
*`The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The modified set is:
{2, 4, 6, 8, 10}`*
更改集合元素的数据类型
我们还可以使用集合理解来更改集合元素的数据类型,如下例所示。这里,我们已经将集合中的所有整数元素转换为字符串。
*`mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
newSet = {str(element) for element in mySet }
print("The existing set is:")
print(mySet)
print("The Newly Created set is:")
print(newSet)`*
输出:
*`The existing set is:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
The Newly Created set is:
{'2', '4', '8', '6', '3', '7', '1', '10', '5', '9'}`*
结论
在本文中,我们讨论了 Python 中的集合理解。我们还查看了它的语法和示例,以便更好地理解这个概念。要了解更多关于其他数据结构的知识,可以阅读这篇关于 Python 中的链表的文章。
在 Python 中设置差异
原文:https://www.pythonforbeginners.com/basics/set-difference-in-python
集合用于存储唯一的对象。有时,我们可能需要在一个集合中找到在另一个集合中不存在的元素。为此,我们使用集合差运算。在本文中,我们将讨论什么是集合差。我们还将讨论在 python 中寻找集合差异的方法。
集合差是什么?
当我们给定两个集合 A 和 b 时。集合差(A-B)是由属于 A 但不在集合 b 中的所有元素组成的集合
同样,集合差(B-A)是由属于 B 但不在集合 A 中的所有元素组成的集合。
考虑以下集合。
A={1,2,3,4,5,6,7}
B={5,6,7,8,9,10,11}
这里,集合 A-B 将包含元素 1、2、3 和 4,因为这些元素存在于集合 A 中但不属于集合 B。类似地,集合B-A将包含元素 8、9、10、11,因为这些元素存在于集合 B 中但不属于集合 A。
现在让我们讨论在 python 中寻找集合差异的方法。
如何在 Python 中求集合差?
给定集合 A 和 B,如果我们想找到集合差 A-B,我们将首先创建一个名为output_set的空集。之后,我们将使用 for 循环遍历集合 A。在遍历时,我们将检查每个元素是否出现在集合 B 中。如果集合 A 中的任何元素不属于集合 B,我们将使用add()方法将该元素添加到output_set中。
执行 for 循环后,我们将在output_set中获得设定的差值 A-B。您可以在下面的示例中观察到这一点。
A = {1, 2, 3, 4, 5, 6, 7}
B = {5, 6, 7, 8, 9, 10, 11}
output_set = set()
for element in A:
if element not in B:
output_set.add(element)
print("The set A is:", A)
print("The set B is:", B)
print("The set A-B is:", output_set)
输出:
The set A is: {1, 2, 3, 4, 5, 6, 7}
The set B is: {5, 6, 7, 8, 9, 10, 11}
The set A-B is: {1, 2, 3, 4}
如果我们想找到集合差 B-A,我们将使用 for 循环遍历集合 B。在遍历时,我们将检查每个元素是否出现在集合 A 中。如果集合 B 中的任何元素不属于集合 A,我们将使用add() 方法将该元素添加到output_set中。
在执行 for 循环后,我们将在output_set中得到设定的差值 B-A。您可以在下面的示例中观察到这一点。
A = {1, 2, 3, 4, 5, 6, 7}
B = {5, 6, 7, 8, 9, 10, 11}
output_set = set()
for element in B:
if element not in A:
output_set.add(element)
print("The set A is:", A)
print("The set B is:", B)
print("The set B-A is:", output_set)
输出:
The set A is: {1, 2, 3, 4, 5, 6, 7}
The set B is: {5, 6, 7, 8, 9, 10, 11}
The set B-A is: {8, 9, 10, 11}
使用 Python 中的 Difference()方法查找集合差异
Python 为我们提供了difference()方法来寻找集合差异。在集合 A 上调用difference() 方法时,将集合 B 作为输入参数,计算集合差,并返回包含集合中元素的集合(A-B)。您可以在下面的示例中观察到这一点。
A = {1, 2, 3, 4, 5, 6, 7}
B = {5, 6, 7, 8, 9, 10, 11}
output_set = A.difference(B)
print("The set A is:", A)
print("The set B is:", B)
print("The set A-B is:", output_set)
输出:
The set A is: {1, 2, 3, 4, 5, 6, 7}
The set B is: {5, 6, 7, 8, 9, 10, 11}
The set A-B is: {1, 2, 3, 4}
结论
在本文中,我们讨论了如何在 python 中找到集合差。要了解更多关于集合的知识,你可以阅读这篇关于 python 中集合理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
Python 中的集合运算
原文:https://www.pythonforbeginners.com/basics/set-operations-in-python
集合是包含唯一元素的容器对象。在本文中,我们将研究各种集合运算,如并集、交集和集合差。我们还将在 python 中实现 set 操作。
联合操作
如果我们给定两个集合 A 和 B,这两个集合的并集被计算为包含集合 A 和集合 B 中的元素的集合。我们使用符号∨表示集合并集运算。
如果我们有一个集合 C 是 A 和 B 的并集,我们可以写 C = A∩B .例如,假设我们有集合 A={1,2,3,4,5 },集合 B = {2,4,6,8},那么集合 C = A∩B 将包含元素{1,2,3,4,5,6,8 }。你可以观察到 C 中的每个元素要么属于 A,要么属于 B,要么同时属于 A 和 B。
我们可以使用 union()方法在 python 中实现 set union 操作。在集合 A 上调用 union()方法时,它将另一个集合 B 作为输入参数,并返回由 A 和 B 的并集构成的集合。
`A = {1, 2, 3, 4, 5}
B = {2, 4, 6, 8}
print("Set A is:", A)
print("Set B is:", B)
C = A.union(B)
print("Union of A and B is:", C)`
输出:
`Set A is: {1, 2, 3, 4, 5}
Set B is: {8, 2, 4, 6}
Union of A and B is: {1, 2, 3, 4, 5, 6, 8}`
我们可以同时执行两个以上集合的联合。在这种情况下,由 union 运算创建的集合包含参与 union 运算的每个集合中的元素。例如,如果我们设置了 A= {1,2,3,4,5},B= {2,4,6,8,10},C={ 7,8,9,10},那么结果集 D = A∩B∩C 将包含元素{1,2,3,4,5,6,7,8,9,10 }。
我们可以在 python 中执行两个以上集合的并集,方法是在 union()方法上调用其他集合作为输入,如下所示。
`A = {1, 2, 3, 4, 5}
B = {2, 4, 6, 8}
C = {7, 8, 9, 10}
print("Set A is:", A)
print("Set B is:", B)
print("Set C is:", C)
D = A.union(B, C)
print("Union of A, B and C is:", D)`
输出:
`Set A is: {1, 2, 3, 4, 5}
Set B is: {8, 2, 4, 6}
Set C is: {8, 9, 10, 7}
Union of A, B and C is: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}`
交集运算
如果我们给定两个集合 A 和 B,则这两个集合的交集被计算为包含集合 A 和集合 B 中都存在的那些元素的集合。我们使用 ∩ 符号来表示集合交集运算。
如果我们有一个集合 C 是 A 和 B 的交集,我们可以写 C= A ∩ B. 例如,假设我们有集合 A={1,2,3,4,5,6 },集合 B = {2,4,6,8},那么集合 C= A ∩ B 将包含元素{2,4,6 }。你可以观察到 C 中的每个元素同时属于 A 或者和 b。
我们可以使用 intersection()方法在 python 中实现设置交集操作。在集合 A 上调用 intersection()方法时,它将另一个集合 B 作为输入参数,并返回由 A 和 B 的交集形成的集合。
`A = {1, 2, 3, 4, 5, 6}
B = {2, 4, 6, 8}
print("Set A is:", A)
print("Set B is:", B)
C = A.intersection(B)
print("Intersection of A and B is:", C)`
输出:
`Set A is: {1, 2, 3, 4, 5, 6}
Set B is: {8, 2, 4, 6}
Intersection of A and B is: {2, 4, 6}`
我们可以同时执行两个以上集合的交集。在这种情况下,由交集运算创建的集合包含参与交集运算的每个集合中存在的元素。例如,如果我们设置 A= {1,2,3,4,5,6},设置 B= {2,4,6,8,10},设置 C={2,4,7,8,9,10},那么结果集 D= A ∩ B ∩ C 将包含元素{ 2,4}。
在 python 中,当对单个集合调用 intersection()方法时,我们可以通过将其他集合作为输入来执行两个以上集合的交集,如下所示。
`A = {1, 2, 3, 4, 5, 6}
B = {2, 4, 6, 8, 10}
C = {2, 4, 7, 8, 9, 10}
print("Set A is:", A)
print("Set B is:", B)
print("Set C is:", C)
D = A.intersection(B, C)
print("Intersection of A, B and C is:", D)`
输出:
`Set A is: {1, 2, 3, 4, 5, 6}
Set B is: {2, 4, 6, 8, 10}
Set C is: {2, 4, 7, 8, 9, 10}
Intersection of A, B and C is: {2, 4}`
集合差分运算
如果给我们两个集合 A 和 B,则集合 A 和集合 B 的差被计算为包含那些存在于集合 A 中但不存在于集合 B 中的元素的集合。我们使用符号–表示集合差运算。
如果我们有一个集合 C 是 A 和 B 的差,我们可以写成 C = A–B .例如,假设我们设 A={1,2,3,4,5,6 },集合 B = {2,4,6,8},那么集合 C = A–B 将包含元素{1,3,5 }。你可以观察到,C 中的每个元素都属于 A,但不属于 b。****
我们可以使用 difference()方法在 python 中实现 set difference 操作。在集合 A 上调用 difference()方法时,该方法将另一个集合 B 作为输入参数,并返回由 A 和 B 的差形成的集合。
**`A = {1, 2, 3, 4, 5, 6}
B = {2, 4, 6, 8}
print("Set A is:", A)
print("Set B is:", B)
C = A.difference(B)
print("Difference of A and B is:", C)`**
输出:
**`Set A is: {1, 2, 3, 4, 5, 6}
Set B is: {8, 2, 4, 6}
Difference of A and B is: {1, 3, 5}`**
结论
在本文中,我们讨论了不同的集合运算。我们还使用集合在 python 中实现了它们。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 中的浅层复制和深层复制
原文:https://www.pythonforbeginners.com/functions/shallow-copy-and-deep-copy-in-python
在编程时,我们需要复制现有的数据。当我们使用=操作符将一个变量赋给另一个变量时,赋值操作符不会复制对象,而只是创建一个对同一个对象的新引用。在本文中,我们将学习如何使用 python 中的浅层复制和深层复制来复制对象。我们也将实施一些项目来理解他们的工作。
python 中如何使用浅层复制?
浅层复制是一种用于创建现有集合对象副本的功能。当我们尝试使用浅层复制来复制集合对象时,它会创建一个新的集合对象,并存储对原始对象的元素的引用。
我们可以通过复制模块在 python 中使用浅层复制。为了执行浅层复制操作,我们使用 copy()模块的 copy()方法。
copy()方法将原始集合对象作为输入,并参考原始集合对象的元素创建一个新的集合对象。然后,它返回对新集合对象的引用。
在下面的程序中,我们将使用 copy()方法创建给定的 python 字典的副本。
import copy
myDict={1:3,4:9,6:12,5:11}
print("Original Dictionary is:")
print(myDict)
newDict=copy.copy(myDict)
print("New Dictionary is:")
print(newDict)
输出:
Original Dictionary is:
{1: 3, 4: 9, 6: 12, 5: 11}
New Dictionary is:
{1: 3, 4: 9, 6: 12, 5: 11}
在输出中,我们可以看到我们创建了一个与程序中给出的原始字典相似的字典。
浅层复制是如何工作的?
在浅层复制中,当创建新对象时,它引用原始对象的元素。如果我们试图对新创建的对象进行任何更改,这将不会反映在原始对象中,因为对象中的元素不应引用另一个对象,即不应有任何嵌套。
import copy
myDict={1:3,4:9,6:12,5:11}
print("Original Dictionary is:")
print(myDict)
newDict=copy.copy(myDict)
print("New Dictionary is:")
print(newDict)
newDict[1]=5
print("Original Dictionary after change is:")
print(myDict)
print("New Dictionary after change is:")
print(newDict)
输出:
Original Dictionary is:
{1: 3, 4: 9, 6: 12, 5: 11}
New Dictionary is:
{1: 3, 4: 9, 6: 12, 5: 11}
Original Dictionary after change is:
{1: 3, 4: 9, 6: 12, 5: 11}
New Dictionary after change is:
{1: 5, 4: 9, 6: 12, 5: 11}
如果我们要对原始对象进行任何更改,这也不会反映在原始对象的副本中,因为不应进行嵌套。
import copy
myDict={1:3,4:9,6:12,5:11}
print("Original Dictionary is:")
print(myDict)
newDict=copy.copy(myDict)
print("New Dictionary is:")
print(newDict)
myDict[1]=5
print("Original Dictionary after change is:")
print(myDict)
print("New Dictionary after change is:")
print(newDict)
输出:
Original Dictionary is:
{1: 3, 4: 9, 6: 12, 5: 11}
New Dictionary is:
{1: 3, 4: 9, 6: 12, 5: 11}
Original Dictionary after change is:
{1: 5, 4: 9, 6: 12, 5: 11}
New Dictionary after change is:
{1: 3, 4: 9, 6: 12, 5: 11}
同样,当我们向原始对象添加任何元素时,它不会对新对象产生任何影响。
import copy
myDict={1:3,4:9,6:12,5:11}
print("Original Dictionary is:")
print(myDict)
newDict=copy.copy(myDict)
print("New Dictionary is:")
print(newDict)
myDict[7]=49
print("Original Dictionary after change is:")
print(myDict)
print("New Dictionary after change is:")
print(newDict)
输出:
Original Dictionary is:
{1: 3, 4: 9, 6: 12, 5: 11}
New Dictionary is:
{1: 3, 4: 9, 6: 12, 5: 11}
Original Dictionary after change is:
{1: 3, 4: 9, 6: 12, 5: 11, 7: 49}
New Dictionary after change is:
{1: 3, 4: 9, 6: 12, 5: 11}
当对象中存在嵌套时,上面讨论的场景会发生变化。即,当被复制的对象包含其他对象时,嵌套对象上发生的变化在原始对象和复制对象中都是可见的。这可以看如下。
import copy
myDict={1:3,4:9,6:12,5:{10:11}}
print("Original Dictionary is:")
print(myDict)
newDict=copy.copy(myDict)
print("New Dictionary is:")
print(newDict)
myDict[5][10]=49
print("Original Dictionary after change is:")
print(myDict)
print("New Dictionary after change is:")
print(newDict)
输出:
Original Dictionary is:
{1: 3, 4: 9, 6: 12, 5: {10: 11}}
New Dictionary is:
{1: 3, 4: 9, 6: 12, 5: {10: 11}}
Original Dictionary after change is:
{1: 3, 4: 9, 6: 12, 5: {10: 49}}
New Dictionary after change is:
{1: 3, 4: 9, 6: 12, 5: {10: 49}}
这是因为当我们使用 copy.copy()方法复制一个对象时,只创建了作为参数传递给 copy()方法的对象的副本。不复制对象内部的元素,只复制对这些元素的引用。因此,当只有原始数据类型(如 int、double、string)作为元素出现在原始对象中时,在原始对象中完成的更改对新对象是不可见的,因为这些数据类型是不可变的,并且对于每个更改,都会创建一个新对象。但是在嵌套对象的情况下,引用是不变的,当我们对其中一个对象进行任何更改时,它在另一个对象中是可见的。
python 中如何使用深度复制?
为了避免在进行浅层复制时讨论的问题,我们将使用 deepcopy()方法。deepcopy()方法递归地创建对象中每个元素的副本,并且不复制引用。这可以如下进行。
import copy
myDict={1:3,4:9,6:12,5:{10:11}}
print("Original Dictionary is:")
print(myDict)
newDict=copy.deepcopy(myDict)
print("New Dictionary is:")
print(newDict)
输出:
Original Dictionary is:
{1: 3, 4: 9, 6: 12, 5: {10: 11}}
New Dictionary is:
{1: 3, 4: 9, 6: 12, 5: {10: 11}}
使用 deepcopy()后,即使存在嵌套,在原始对象中所做的更改也不会显示在复制的对象中。这可以看如下。
import copy
myDict={1:3,4:9,6:12,5:{10:11}}
print("Original Dictionary is:")
print(myDict)
newDict=copy.deepcopy(myDict)
print("New Dictionary is:")
print(newDict)
myDict[5][10]=49
print("Original Dictionary after change is:")
print(myDict)
print("New Dictionary after change is:")
print(newDict)
输出:
Original Dictionary is:
{1: 3, 4: 9, 6: 12, 5: {10: 11}}
New Dictionary is:
{1: 3, 4: 9, 6: 12, 5: {10: 11}}
Original Dictionary after change is:
{1: 3, 4: 9, 6: 12, 5: {10: 49}}
New Dictionary after change is:
{1: 3, 4: 9, 6: 12, 5: {10: 11}}
这里我们可以看到,与 copy()不同,当我们使用 deepcopy()复制对象时,在原始对象中所做的更改不会影响复制的对象,反之亦然,因为由 deepcopy()方法创建的对象不包含对原始字典元素的任何引用,而在 copy()方法的情况下,新创建的对象包含对原始对象元素的引用。
结论
在本文中,我们讨论了 python 中的浅层复制和深层复制。我们已经看到,当存在嵌套对象时,应该使用 deepcopy()来创建对象的副本。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。
在 Python 中注释掉多行的快捷方式
原文:https://www.pythonforbeginners.com/comments/shortcut-to-comment-out-multiple-lines-in-python
在测试或调试代码时,我们经常需要注释掉 python 中的代码块。当一个块被转换成 python 注释时,它不会影响程序的输出,而是帮助确定哪个函数或块在程序中产生错误。本文讨论了在不同的 python IDEs 中一次注释掉多行代码的快捷方式。让我们逐一查看每个 IDE 的示例。
在 Spyder IDE 中注释掉多行的快捷方式
在 spyder python IDE 中,我们可以通过选择一行代码,然后使用组合键ctrl+1来注释该行代码。这将把选中的单行变成注释,如下所示。示例中给出的函数将一个数字及其平方作为键值对添加到一个 python 字典中。
print("This line will be commented out.")
def add_square_to_dict(x,mydict):
a=x*x
mydict[str(x)]=a
return mydict
按下ctrl+1后:
#print("This line will be commented out.")
def add_square_to_dict(x,mydict):
a=x*x
mydict[str(x)]=a
return mydict
在 spyder IDE 中注释掉多行代码的快捷方式是先选中所有需要注释掉的行,然后按组合键ctrl+4。这将把所有选中的行变成一个 python 注释,如下所示。
class MyNumber():
"""This is the docstring of this class.
It describes what this class does and all its attributes."""
def __init__(self, value):
self.value=value
def increment(self):
"""This is the docstring for this method.
It describes what the method does, what are its calling conventions and
what are its side effects"""
self.value=self.value+1
return self.value
print (MyNumber.increment.__doc__)
按下 ctrl+4 后:
# =============================================================================
#
# class MyNumber():
# """This is the docstring of this class.
#
# It describes what this class does and all its attributes."""
# def __init__(self, value):
# self.value=value
# def increment(self):
# """This is the docstring for this method.
#
# It describes what the method does, what are its calling conventions and
# what are its side effects"""
# self.value=self.value+1
# return self.value
# print (MyNumber.increment.__doc__)
# =============================================================================
如何在 Spyder IDE 中取消代码注释?
- 当代码行被注释掉时,我们可以在选择代码行后使用
ctrl+1取消注释。 - 在 Spyder 的某些版本中,
ctrl+5可以用来取消代码行的注释。
注释掉空闲多行的快捷方式
要注释掉空闲状态下的代码块,我们必须首先选择该行,然后按组合键ctrl+D。这将注释掉选定的代码行,如下所示。
class MyNumber():
"""This is the docstring of this class.
It describes what this class does and all its attributes."""
def __init__(self, value):
self.value=value
def increment(self):
"""This is the docstring for this method.
It describes what the method does, what are its calling conventions and
what are its side effects"""
self.value=self.value+1
return self.value
print (MyNumber.increment.__doc__)
按下ctrl+D后,代码行将被注释掉,如下所示。
## class MyNumber():
## """This is the docstring of this class.
##
## It describes what this class does and all its attributes."""
## def __init__(self, value):
## self.value=value
## def increment(self):
## """This is the docstring for this method.
##
## It describes what the method does, what are its calling conventions and
## what are its side effects"""
## self.value=self.value+1
## return self.value
## print (MyNumber.increment.__doc__)
取消空闲代码的注释
要取消 IDLE 中代码行的注释,我们只需选择代码行,然后按下ctrl+shift+d。这将取消对选定行的注释。
在 Jupyter 笔记本中注释掉多行的快捷方式
我们可以使用ctrl+/注释掉 Jupyter Notebook 中选中的 python 代码行。这将选定的代码行变成注释,如下所示。
class MyNumber():
"""This is the docstring of this class.
It describes what this class does and all its attributes."""
def __init__(self, value):
self.value=value
def increment(self):
"""This is the docstring for this method.
It describes what the method does, what are its calling conventions and
what are its side effects"""
self.value=self.value+1
return self.value
print (MyNumber.increment.__doc__)
按下ctrl+/后,代码会被注释掉,如下图所示。
# class MyNumber():
# """This is the docstring of this class.
# It describes what this class does and all its attributes."""
# def __init__(self, value):
# self.value=value
# def increment(self):
# """This is the docstring for this method.
# It describes what the method does, what are its calling conventions and
# what are its side effects"""
# self.value=self.value+1
# return self.value
# print (MyNumber.increment.__doc__)
取消 Jupyter 笔记本中代码的注释
要取消 Jupyter 笔记本中所选行的注释,我们只需再次按下ctrl+/。这将取消 Jupyter 笔记本中代码的注释。
在 PyCharm 中注释掉多行
如果我们必须在 Pycharm 中注释掉多行代码,我们可以选择要注释掉的行,然后按ctrl+shift+/。在这之后,这些行将从代码中被注释掉。
取消 PyCharm 中代码的注释
要取消 PyCharm 中代码的注释,我们只需选择代码行,然后再次按下ctrl+shift+/。在此之后,评论将被转化为代码。
结论
在本文中,我们看到了在 python 不同的 ide 中一次注释掉多行的快捷方式,如 spyder、IDLE、Jupyter Notebook 和 PyCharm。
要了解更多关于 python 编程的知识,可以阅读这篇关于 python 中的字符串操作的文章。你可能也会喜欢这篇关于 python simplehttpserver 的文章。
请继续关注更多内容丰富的文章。
图中从一个顶点到其它顶点的最短路径长度
图形用于表示地理地图、计算机网络等。在本文中,我们将讨论如何计算未加权图中顶点之间的最短距离。为了计算从一个顶点到其他顶点的最短路径长度,我们将使用广度优先搜索算法。
如何计算一个顶点到其他顶点的最短路径长度?
在未加权的图中,所有的边都有相等的权重。这意味着我们只需计算每个顶点之间的边数,就可以计算出它们之间的最短路径长度。
例如,考虑下图。

Graph in Python
让我们计算上图中每个顶点之间的最短距离。
顶点 A 和顶点 b 之间只有一条边 E ₂ 所以,它们之间的最短路径长度是 1。
我们可以用两种方法从 A 到达 C。第一种是使用边 E₄->E₅->E₆,第二种是使用边 E ₂ - > E₆ 。这里我们将选择最短路径,即 E ₂ - > E₆ 。因此,顶点 A 和顶点 C 之间的最短路径长度是 2。
顶点 A 和顶点 d 之间只有一条边 E ₁ 所以,它们之间的最短路径长度是 1。
顶点 A 和顶点 E 之间只有一条边 E₃ 所以,它们之间的最短路径长度是 1。
我们可以用两种方法从 A 到达 F。第一条路径使用边 E ₂ - > E₅ ,第二条路径使用边 E₄ 。这里,我们将选择最短路径,即₄ 。因此,顶点 A 和顶点 F 之间的最短路径长度是 1。
计算从一个顶点到其它顶点最短路径长度的算法
到现在为止,你一定已经明白我们必须计算顶点之间的边数来计算顶点之间的距离。为此,我们将如下修改广度优先搜索算法。
- 我们将声明一个 python 字典,它将包含顶点作为它们的键,以及到源顶点的距离作为关联值。
- 最初,我们将把每个顶点到源的距离指定为无穷大,用一个大的数字表示。每当我们在遍历过程中找到一个顶点时,我们将计算该顶点到源的当前距离。如果当前距离小于包含源和其他顶点之间距离的字典中提到的距离,我们将更新字典中的距离。
- 在全宽度优先遍历之后,我们将得到包含从源到每个顶点的最小距离的字典。
我们可以将用于计算未加权图的顶点之间的最短路径长度的算法公式化如下。
- 创建一个空队列。
- 创建一个 visited_vertices 列表来跟踪已访问的顶点。
- 创建一个字典 distance_dict 来跟踪顶点到源顶点的距离。将距离初始化为 99999999。
- 将源顶点插入 Q 和 visited_vertices。
- 如果 Q 为空,则返回。否则转到 6。
- 从 q 中取出一个顶点 v。
- 更新 distance_dict 中 v 的未访问邻居的距离。
- 将未访问的相邻顶点插入 Q 和已访问的顶点。
- 转到第 5 页。
履行
因为我们已经讨论了这个例子,并且制定了一个算法来寻找图中源顶点和其他顶点之间的最短路径长度,所以让我们用 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 calculate_distance(input_graph, source):
Q = Queue()
distance_dict = {k: 999999999 for k in input_graph.keys()}
visited_vertices = list()
Q.put(source)
visited_vertices.append(source)
while not Q.empty():
vertex = Q.get()
if vertex == source:
distance_dict[vertex] = 0
for u in input_graph[vertex]:
if u not in visited_vertices:
# update the distance
if distance_dict[u] > distance_dict[vertex] + 1:
distance_dict[u] = distance_dict[vertex] + 1
Q.put(u)
visited_vertices.append(u)
return distance_dict
distances = calculate_distance(graph, "A")
for vertex in distances:
print("Shortest Path Length to {} from {} is {}.".format(vertex, "A", distances[vertex]))
输出:
Given Graph is:
{'A': ['B', 'D', 'E', 'F'], 'D': ['A'], 'B': ['A', 'F', 'C'], 'F': ['B', 'A'], 'C': ['B'], 'E': ['A']}
Shortest Path Length to A from A is 0.
Shortest Path Length to D from A is 1.
Shortest Path Length to B from A is 1.
Shortest Path Length to C from A is 2.
Shortest Path Length to E from A is 1.
结论
在本文中,我们讨论并实现了计算无权图中顶点间最短路径长度的算法。这里我们使用了广度优先图遍历算法。要了解二叉树遍历算法,可以阅读中的有序树遍历算法或中的层次有序树遍历算法。
Python 中的单行和多行注释
原文:https://www.pythonforbeginners.com/comments/single-line-and-multi-line-comments-in-python
注释是一段代码,当程序被执行时,它不会被编译器或解释器执行。只有当我们能够访问源代码时,才能阅读注释。注释用于解释源代码,使代码更具可读性和可理解性。在本文中,我们将看到如何使用 python 中的不同方法编写单行和多行注释。
python 中的单行注释是什么?
单行注释是那些在 python 中没有换行或者换行的注释。一个 python 注释通过用一个#初始化注释文本来编写,并在遇到行尾时终止。下面的例子显示了一个程序中的单行注释,其中定义了一个函数,将一个数字及其平方作为键值对添加到 python 字典中。
#This is a single line comment in python
def add_square_to_dict(x,mydict):
a=x*x
mydict[str(x)]=a
return mydict
我们也可以在另一个语句后添加单行注释。
#This is a single line comment in python
print("Pythonforbeginners.com") #This is also a python comment
什么是多行注释?
顾名思义,多行注释可以扩展到多行。但是 python 没有多行注释的语法。我们可以使用单行注释或三重引用的 python 字符串在 python 中实现多行注释。
如何使用#符号实现多行注释?
为了使用#符号实现多行注释,我们可以简单地将多行注释的每一行描述为单行注释。然后我们可以用符号#开始每一行,我们可以实现多行注释。
#This is a multiline comment in python
#and expands to more than one line
print("Pythonforbeginners.com")
当使用#符号编写多行注释时,我们也可以在任何 python 语句后开始多行注释。
#This is a multiline comment in python
#and expands to more than one line
print("Pythonforbeginners.com") #This is also a python comment
#and it also expands to more than one line.
如何使用三重引号字符串实现多行注释?
python 中的多行字符串如果没有赋给变量,可以用作多行注释。当字符串没有被赋给任何变量时,它们会被解释器解析和评估,但不会生成字节码,因为没有地址可以赋给字符串。实际上,未赋值的多行字符串作为多行注释工作。
"""This is
a
multiline comment in python
which expands to many lines"""
在这里,我们必须记住,多行注释只是字符串常量,没有被赋予任何变量。所以它们必须有正确的意图,不像带有#符号的单行注释,这样可以避免语法错误。
此外,使用三重引号的多行注释应该总是以换行符开始,这与单行注释不同。
#This is a multiline comment in python
#and expands to more than one line
"""This is
a
multiline comment in python
which expands to many lines"""
print("Pythonforbeginners.com") """This is not
a
multiline comment in python
and will cause syntax error"""
结论
在本文中,我们看到了如何用 python 编写单行和多行注释。我们还看到了如何使用字符串编写多行注释。请继续关注更多内容丰富的文章。
用 Python 对熊猫系列进行排序
原文:https://www.pythonforbeginners.com/basics/sort-a-pandas-series-in-python
Pandas 系列用于处理 python 中的顺序数据。在本文中,我们将讨论在 Python 中对熊猫系列进行排序的不同方法。
使用 sort_values()方法对序列进行排序
您可以使用sort_values()方法对熊猫系列进行排序。它具有以下语法。
Series.sort_values(*, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)
这里,
axis参数用于决定我们是否要按列或行对数据帧进行排序。对于系列,不使用axis参数。定义它只是为了让sort_values()方法与熊猫数据帧兼容。- 默认情况下,
sort_values()方法按升序对序列进行排序。如果您想按降序对一个系列进行排序,您可以将ascending参数设置为 True。 - 执行后,
sort_values()方法返回排序后的序列。它不会修改原始系列。要对原始序列进行排序和修改,而不是创建一个新序列,您可以将inplace参数设置为True。 kind参数用于确定排序算法。默认情况下,使用“quicksort”算法。如果您的数据具有特定的模式,而另一种排序算法可能是有效的,那么您可以使用‘mergesort’、‘heapsort’或‘stable’排序算法。na_position参数用于确定 NaN 值在排序序列中的位置。默认情况下,NaN 值存储在排序序列的最后。您可以将na_position参数设置为“first”来存储排序序列顶部的 NaN 值。- 当我们对一个序列进行排序时,所有值的索引在排序时会被打乱。因此,排序序列中的索引是无序的。如果您想在排序后重置索引,您可以将
ignore_index参数设置为 True。 key参数用于在排序前对系列执行操作。它接受一个矢量化函数作为其输入参数。提供给key参数的函数必须将熊猫系列作为其输入参数,并返回熊猫系列。排序前,该函数应用于系列。然后,函数输出中的值用于对序列进行排序。
在 Python 中对序列进行升序排序
要按升序对系列进行排序,可以对 series 对象使用sort_values() 方法,如下例所示。
import pandas as pd
numbers=[12,34,11,25,27,8,13]
series=pd.Series(numbers)
print("The original series is:")
print(series)
sorted_series=series.sort_values()
print("The sorted series is:")
print(sorted_series)
输出:
The original series is:
0 12
1 34
2 11
3 25
4 27
5 8
6 13
dtype: int64
The sorted series is:
5 8
2 11
0 12
6 13
3 25
4 27
1 34
dtype: int64
在上面的例子中,我们首先创建了一个有 7 个数字的熊猫系列。然后,我们使用sort_values()方法对序列进行排序。
您可以观察到,在对序列进行排序时,索引也随着序列中的值进行了洗牌。要重置索引,您可以将ignore_index参数设置为 True,如下所示。
import pandas as pd
numbers=[12,34,11,25,27,8,13]
series=pd.Series(numbers)
print("The original series is:")
print(series)
sorted_series=series.sort_values(ignore_index=True)
print("The sorted series is:")
print(sorted_series)
输出:
The original series is:
0 12
1 34
2 11
3 25
4 27
5 8
6 13
dtype: int64
The sorted series is:
0 8
1 11
2 12
3 13
4 25
5 27
6 34
dtype: int64
在这个例子中,您可以观察到由sort_values() 方法返回的序列具有从 0 到 6 的索引,而不是混洗的索引。
按降序排列熊猫系列
要按降序对熊猫系列进行排序,可以将参数sort_values()中的参数ascending设置为 False。执行后,sort_values()方法将返回一个降序排列的序列。您可以在下面的示例中观察到这一点。
import pandas as pd
numbers=[12,34,11,25,27,8,13]
series=pd.Series(numbers)
print("The original series is:")
print(series)
sorted_series=series.sort_values(ascending=False,ignore_index=True)
print("The sorted series is:")
print(sorted_series)
输出:
The original series is:
0 12
1 34
2 11
3 25
4 27
5 8
6 13
dtype: int64
The sorted series is:
0 34
1 27
2 25
3 13
4 12
5 11
6 8
dtype: int64
在上面的例子中,我们已经将sort_values()方法中的ascending参数设置为 False。因此,在执行了sort_values()方法之后,我们得到了一个降序排列的序列。
在 Python 中对具有 NaN 值的序列进行排序
要用 NaN 值对 pandas 系列进行排序,只需调用 pandas 系列的 sort_values()方法,如下例所示。
import pandas as pd
import numpy as np
numbers=[12,np.nan,11,np.nan,27,-8,13]
series=pd.Series(numbers)
print("The original series is:")
print(series)
series.sort_values(inplace=True,ignore_index=True)
print("The sorted series is:")
print(series)
输出:
The original series is:
0 12.0
1 NaN
2 11.0
3 NaN
4 27.0
5 -8.0
6 13.0
dtype: float64
The sorted series is:
0 -8.0
1 11.0
2 12.0
3 13.0
4 27.0
5 NaN
6 NaN
dtype: float64
在此示例中,您可以观察到该系列包含 NaN 值。因此,默认情况下,sort_values()方法将 NaN 值放在排序序列的最后。如果您希望 NaN 值位于排序后的序列的开始处,您可以将na_position参数设置为“first” ,如下所示。
import pandas as pd
import numpy as np
numbers=[12,np.nan,11,np.nan,27,-8,13]
series=pd.Series(numbers)
print("The original series is:")
print(series)
series.sort_values(inplace=True,ignore_index=True,na_position="first")
print("The sorted series is:")
print(series)
输出:
The original series is:
0 12.0
1 NaN
2 11.0
3 NaN
4 27.0
5 -8.0
6 13.0
dtype: float64
The sorted series is:
0 NaN
1 NaN
2 -8.0
3 11.0
4 12.0
5 13.0
6 27.0
dtype: float64
在上面的两个例子中,您可以观察到序列的数据类型被设置为float64,不像前面的例子中序列的数据类型被设置为int64。这是因为在 python 中 NaN 值被认为是浮点数据类型。因此,所有数字都被转换为最兼容的数据类型。
在 Python 中就地排序系列
在上面的例子中,您可以观察到原始序列没有被修改,我们得到了一个新的排序序列。如果您想对序列进行就地排序,您可以将inplace参数设置为 True,如下所示。
import pandas as pd
numbers=[12,34,11,25,27,8,13]
series=pd.Series(numbers)
print("The original series is:")
print(series)
series.sort_values(inplace=True,ignore_index=True)
print("The sorted series is:")
print(series)
输出:
The original series is:
0 12
1 34
2 11
3 25
4 27
5 8
6 13
dtype: int64
The sorted series is:
0 8
1 11
2 12
3 13
4 25
5 27
6 34
dtype: int64
在这个例子中,我们已经在sort_values()方法中将inplace参数设置为 True。因此,在执行了sort_values()方法之后,原始序列被排序,而不是创建一个新的熊猫序列。在这种情况下,sort_values()方法返回 None。
使用关键字对熊猫系列进行排序
默认情况下,序列中的值用于排序。现在,假设您想根据数值的大小而不是实际值对序列进行排序。为此,您可以使用 keys 参数。
我们将把abs() 函数传递给sort_values()方法的key参数。在此之后,序列的值将按其大小排序。您可以在下面的示例中观察到这一点。
import pandas as pd
numbers=[12,-34,11,-25,27,-8,13]
series=pd.Series(numbers)
print("The original series is:")
print(series)
series.sort_values(inplace=True,ignore_index=True,key=abs)
print("The sorted series is:")
print(series)
输出:
The original series is:
0 12
1 -34
2 11
3 -25
4 27
5 -8
6 13
dtype: int64
The sorted series is:
0 -8
1 11
2 12
3 13
4 -25
5 27
6 -34
dtype: int64
在这个例子中,我们有一系列正数和负数。现在,为了使用数字的绝对值对熊猫系列进行排序,我们在 sort_values() 方法中使用了key参数。在key参数中,我们传递了abs()函数。
当执行sort_values()方法时,序列的元素首先被传递给abs() 函数。然后,由abs()函数返回的值被用来比较对序列排序的元素。这就是为什么我们得到的序列中的元素是按绝对值而不是实际值排序的。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
Python 中的 sort_index()方法
除了使用值对序列进行排序,我们还可以使用行索引对序列进行排序。为此,我们可以使用sort_index()方法。它具有以下语法。
Series.sort_index(*, axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, ignore_index=False, key=None)
这里,
axis参数的使用方式与sort_values()方法类似。level参数用于当存在多级索引时,按某一级索引对序列进行排序。要按特定顺序按多个索引级别对序列进行排序,可以按相同顺序将级别列表传递给level参数。- 默认情况下,series 对象按索引值升序排序。如果希望输出数据帧中的索引以降序排列,可以将
ascending参数设置为 False。 - 执行后,
sort_values()方法返回排序后的序列。要通过索引对原始序列进行排序和修改,而不是创建一个新序列,可以将inplace参数设置为 True。 kind参数用于确定排序算法。默认情况下,使用“quicksort”算法。如果索引值是一种特定的模式,在这种模式下另一种排序算法可能是有效的,那么您可以使用‘mergesort’、‘heapsort’或‘stable’排序算法。na_position参数用于确定 NaN 索引在排序序列中的位置。默认情况下,NaN 索引存储在排序序列的最后。您可以将na_position参数设置为“first”来存储排序序列顶部的 NaN 索引。sort_index()方法按照特定的顺序(升序或降序)对索引进行排序。在对索引进行排序之后,如果您想要重置序列的索引,您可以将ignore_index参数设置为 True。key参数用于在排序前对系列的索引执行操作。它接受一个矢量化函数作为其输入参数。提供给key参数的函数必须将索引作为其输入参数,并返回一个熊猫系列。在排序之前,该函数应用于索引。然后,函数输出中的值用于对序列进行排序。
按索引升序排列熊猫系列
要按索引升序对 pandas 系列进行排序,可以调用 series 对象上的sort_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 original series is:")
print(series)
sorted_series=series.sort_index()
print("The sorted series is:")
print(sorted_series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The sorted series is:
2 abcd
3 a
11 c
14 ab
16 abc
23 b
45 bc
65 d
dtype: object
在这个例子中,我们有一系列以数字为索引的字符串。由于我们已经对 pandas 系列使用了sort_index()方法进行排序,所以该系列是按索引值排序的。因此,我们得到了一个对索引值进行排序的序列。
排序后,如果要重置输出数据帧的索引,可以在如下所示的sort_index()方法中将ignore_index参数设置为 True。
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 original series is:")
print(series)
sorted_series=series.sort_index(ignore_index=True)
print("The sorted series is:")
print(sorted_series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The sorted series is:
0 abcd
1 a
2 c
3 ab
4 abc
5 b
6 bc
7 d
dtype: object
在这个例子中,我们已经在sort_index()方法中将ignore_index参数设置为 True。因此,在按原始索引值对序列进行排序后,序列的索引将被重置。
在 Python 中按索引降序对序列进行排序
要按索引降序对 pandas 系列进行排序,可以将sort_index()方法中的ascending参数设置为 False,如下例所示。
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 original series is:")
print(series)
sorted_series=series.sort_index(ascending=False)
print("The sorted series is:")
print(sorted_series)
输出:
The original series is:
3 a
23 b
11 c
14 ab
16 abc
2 abcd
45 bc
65 d
dtype: object
The sorted series is:
65 d
45 bc
23 b
16 abc
14 ab
11 c
3 a
2 abcd
dtype: object
在这个例子中,我们将sort_index()方法中的升序参数设置为 False。因此,该系列按索引降序排序。
按具有 NaN 值的索引对熊猫系列进行排序
要在索引中有 NaN 值时按索引对序列进行排序,只需调用 pandas 序列上的sort_index()方法,如下例所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
sorted_series=series.sort_index()
print("The sorted series is:")
print(sorted_series)
输出:
The original series is:
3.0 a
23.0 b
NaN c
14.0 ab
16.0 abc
NaN abcd
45.0 bc
65.0 d
dtype: object
The sorted series is:
3.0 a
14.0 ab
16.0 abc
23.0 b
45.0 bc
65.0 d
NaN c
NaN abcd
dtype: object
在上面的示例中,序列的索引包含 NaN 值。默认情况下,NaN 值存储在排序序列的最后。如果您希望 NaN 值位于排序序列的开始处,您可以将na_position参数设置为 “first”,如下所示。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
sorted_series=series.sort_index(na_position="first")
print("The sorted series is:")
print(sorted_series)
输出:
The original series is:
3.0 a
23.0 b
NaN c
14.0 ab
16.0 abc
NaN abcd
45.0 bc
65.0 d
dtype: object
The sorted series is:
NaN c
NaN abcd
3.0 a
14.0 ab
16.0 abc
23.0 b
45.0 bc
65.0 d
dtype: object
在这个例子中,您可以看到我们已经在sort_index() 方法中将na_position参数设置为"first"。因此,将 NaN 值作为索引的元素被保存在由sort_index()方法返回的排序序列的开始处。
有趣阅读:做程序员的优势。
在 Python 中按索引就地对序列排序
默认情况下,sort_index()方法不会对原始序列进行排序。它返回一个按索引排序的新系列。如果您想要修改原始序列,您可以在如下所示的sort_index()方法中将inplace参数设置为 True。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,np.nan,14,16,np.nan,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series.sort_index(inplace=True)
print("The sorted series is:")
print(series)
输出:
The original series is:
3.0 a
23.0 b
NaN c
14.0 ab
16.0 abc
NaN abcd
45.0 bc
65.0 d
dtype: object
The sorted series is:
3.0 a
14.0 ab
16.0 abc
23.0 b
45.0 bc
65.0 d
NaN c
NaN abcd
dtype: object
在这个例子中,我们已经在sort_index()方法中将inplace参数设置为 True。因此,原始系列被排序,而不是创建新系列。
使用 Python 中的键按索引对熊猫系列进行排序
通过使用key参数,我们可以在按索引对序列排序之前对序列的索引执行操作。例如,如果序列中的索引是负数,并且希望使用索引的大小对序列进行排序,可以将abs()函数传递给sort_index()方法中的key参数。
import pandas as pd
import numpy as np
letters=["a","b","c","ab","abc","abcd","bc","d"]
numbers=[3,23,-100,14,16,-3,45,65]
series=pd.Series(letters)
series.index=numbers
print("The original series is:")
print(series)
series.sort_index(inplace=True,key=abs)
print("The sorted series is:")
print(series)
输出:
The original series is:
3 a
23 b
-100 c
14 ab
16 abc
-3 abcd
45 bc
65 d
dtype: object
The sorted series is:
3 a
-3 abcd
14 ab
16 abc
23 b
45 bc
65 d
-100 c
dtype: object
在这个例子中,我们有一个以正数和负数作为索引的序列。现在,为了使用指数的绝对值对熊猫系列进行排序,我们使用了sort_index()方法中的关键参数。在key参数中,我们传递了abs() 函数。
当执行sort_index()方法时,序列的索引首先被传递给abs()函数。由abs()函数返回的值然后被用来比较排序序列的索引。这就是为什么我们得到的序列中的指数是按绝对值而不是实际值排序的。
结论
在本文中,我们讨论了如何用 Python 对熊猫系列进行排序。为此,我们使用了sort_values()和sort_index()方法。我们使用这些方法的不同参数演示了不同的示例。
我希望你喜欢阅读这篇文章。要了解更多关于 pandas 模块的信息,你可以阅读这篇关于如何对 pandas 数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
快乐学习!
Python 中对象的排序列表
原文:https://www.pythonforbeginners.com/basics/sort-list-of-objects-in-python
我们可以简单地使用sort()方法或sorted()函数对数字列表进行排序。但是,我们不能对使用自定义类创建的对象列表这样做。在本文中,我们将讨论如何使用 python 中的sort()方法和sorted()函数对对象列表进行排序。
如何在 Python 中对对象列表进行排序?
通常,当我们有一个数字列表时,我们可以使用如下所示的sort()方法进行排序。
myList = [1, 2, 9, 3, 6, 17, 8, 12, 10]
print("Original list is:", myList)
myList.sort()
print("The sorted list is:", myList)
输出:
Original list is: [1, 2, 9, 3, 6, 17, 8, 12, 10]
The sorted list is: [1, 2, 3, 6, 8, 9, 10, 12, 17]
现在,让我们尝试对对象列表进行排序。为此,我们将创建一个属性为name和age的Person类。之后,我们将创建不同的 person 对象,并制作一个包含这些对象的列表。当我们试图对列表进行排序时,程序会遇到如下所示的类型错误异常。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)
myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
print(person, end=",")
print("\n")
myList.sort()
print("The sorted list is:", myList)
输出:
Original list is:
Sam,Harry,Tom,John,Kite,Emily,
/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 22, in <module>
myList.sort()
TypeError: '<' not supported between instances of 'Person' and 'Person'
这里发生错误是因为我们不能使用<操作符来比较两个Person对象。因此,我们必须指定一个Person类的属性,用于比较两个不同的 Person 对象。为此,我们在sort()方法中使用了key参数。
我们将首先创建一个函数getAge(),它接受一个Person对象作为输入参数,并返回age。
之后,我们将把getAge()函数赋给key参数。执行后,sort() 方法将对 Person 对象的列表进行排序,如下例所示。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
def getAge(person):
return person.age
person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)
myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
print(person, end=",")
print("\n")
myList.sort(key=getAge)
print("The sorted list is:")
for person in myList:
print(person, end=",")
输出:
Original list is:
Sam,Harry,Tom,John,Kite,Emily,
The sorted list is:
Sam,Tom,Harry,Emily,John,Kite,
如果不允许修改输入列表,可以使用sorted()功能对对象列表进行排序。这里,我们将传递对象列表作为第一个输入参数,传递函数getAge() 作为第二个输入参数。执行后,它将返回一个对象的排序列表,如下所示。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
def getAge(person):
return person.age
person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)
myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
print(person, end=",")
print("\n")
newList = sorted(myList, key=getAge)
print("The sorted list is:")
for person in newList:
print(person, end=",")
输出:
Original list is:
Sam,Harry,Tom,John,Kite,Emily,
The sorted list is:
Sam,Tom,Harry,Emily,John,Kite,
使用 Lambda 函数对对象列表进行排序
我们可以使用 lambda 函数对对象列表进行排序,而不是定义一个不同的函数,比如getAge()。这里,我们将创建一个 lambda 函数,它接受一个对象并返回其属性。然后,我们将把 lambda 函数赋给sort() 方法中的参数键。在执行了sort()方法之后,列表将被排序,如下例所示。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)
myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
print(person, end=",")
print("\n")
myList.sort(key=lambda p: p.age)
print("The sorted list is:")
for person in myList:
print(person, end=",")
输出:
Original list is:
Sam,Harry,Tom,John,Kite,Emily,
The sorted list is:
Sam,Tom,Harry,Emily,John,Kite,
除了使用sort()方法,您还可以使用带有 lambda 函数的sorted()函数对对象列表进行排序,如下例所示。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name
person1 = Person("Sam", 12)
person2 = Person("Harry", 23)
person3 = Person("Tom", 17)
person4 = Person("John", 30)
person5 = Person("Kite", 40)
person6 = Person("Emily", 23)
myList = [person1, person2, person3, person4, person5, person6]
print("Original list is:")
for person in myList:
print(person, end=",")
print("\n")
newList = sorted(myList, key=lambda p: p.age)
print("The sorted list is:")
for person in newList:
print(person, end=",")
输出:
Original list is:
Sam,Harry,Tom,John,Kite,Emily,
The sorted list is:
Sam,Tom,Harry,Emily,John,Kite,
结论
在本文中,我们讨论了如何在 python 中对一列对象进行排序。要了解更多关于 python 中的列表,你可以阅读这篇关于 python 中的列表理解的文章。
Python 中按字母顺序排列的字符串列表
原文:https://www.pythonforbeginners.com/basics/sort-list-of-strings-alphabetically-in-python
在 python 中,我们使用字符串来处理文本数据。在编程时,我们可能需要对 python 中的字符串列表进行排序。在本文中,我们将讨论在 python 中按字母顺序对字符串列表进行排序的不同方法。
使用 Sort()方法按字母顺序对字符串列表进行排序。
为了对列表中的元素进行排序,我们使用了sort()方法。当在列表上调用时,sort()方法对现有列表的元素进行排序。例如,我们可以对数字列表进行如下排序。
myList = [1, 23, 12, 345, 34, 45]
print("The list is:")
print(myList)
myList.sort()
print("The reverse sorted List is:")
print(myList)
输出:
The list is:
[1, 23, 12, 345, 34, 45]
The reverse sorted List is:
[1, 12, 23, 34, 45, 345]
为了按字母顺序对字符串列表进行排序,我们可以使用sort()方法,就像我们使用它对数字列表进行排序一样。列表中的字符串将根据它们的第一个字符进行比较。ASCII 值中第一个字符在前的字符串将位于排序列表的第一个位置。例如,“苹果”在“盒子”之前,就像“a”在“b”之前一样。您可以在下面的示例中观察到这一点。
myList = ["apple","box","tickle","python","button"]
print("The list is:")
print(myList)
myList.sort()
print("The sorted List is:")
print(myList)
输出:
The list is:
['apple', 'box', 'tickle', 'python', 'button']
The sorted List is:
['apple', 'box', 'button', 'python', 'tickle']
如果两个字符串具有相同的第一个字符,将使用第二个字符来比较这两个字符串。类似地,如果两个字符串的第二个字符相同,它们将根据第三个字符在排序列表中排序,依此类推。您可以在下面的示例中观察到这一点。
myList = ["apple", "aaple", "aaaple", "tickle", "python", "button"]
print("The list is:")
print(myList)
myList.sort()
print("The sorted List is:")
print(myList)
输出:
The list is:
['apple', 'aaple', 'aaaple', 'tickle', 'python', 'button']
The sorted List is:
['aaaple', 'aaple', 'apple', 'button', 'python', 'tickle']
您也可以使用参数“reverse”按相反的字母顺序对字符串列表排序,如下所示。
myList = ["apple", "aaple", "aaaple", "tickle", "python", "button"]
print("The list is:")
print(myList)
myList.sort(reverse=True)
print("The reverse sorted List is:")
print(myList)
输出:
The list is:
['apple', 'aaple', 'aaaple', 'tickle', 'python', 'button']
The reverse sorted List is:
['tickle', 'python', 'button', 'apple', 'aaple', 'aaaple']
使用 sorted()函数按字母顺序对字符串列表排序
如果不想修改已有的列表,可以使用sorted()函数对 python 中的字符串列表进行排序。sorted()函数的工作方式类似于sort()方法。唯一的区别是它返回一个新的排序列表,而不是修改原来的列表。
为了按字母顺序对字符串列表进行排序,我们将把字符串列表传递给 sorted()函数,它将返回如下排序列表。
myList = ["apple", "aaple", "aaaple", "tickle", "python", "button"]
print("The list is:")
print(myList)
newList = sorted(myList)
print("The sorted List is:")
print(newList)
输出:
The list is:
['apple', 'aaple', 'aaaple', 'tickle', 'python', 'button']
The sorted List is:
['aaaple', 'aaple', 'apple', 'button', 'python', 'tickle']
这里,对字符串进行排序的机制类似于我们在上一节中讨论的机制。
您也可以使用“reverse”参数按字母顺序对列表进行反向排序,如下所示。
myList = ["apple", "aaple", "aaaple", "tickle", "python", "button"]
print("The list is:")
print(myList)
newList = sorted(myList, reverse=True)
print("The reverse sorted List is:")
print(newList)
输出:
The list is:
['apple', 'aaple', 'aaaple', 'tickle', 'python', 'button']
The reverse sorted List is:
['tickle', 'python', 'button', 'apple', 'aaple', 'aaaple']
结论
在本文中,我们讨论了如何使用sort()方法和sorted()函数在 python 中按字母顺序对字符串列表进行排序。我们还讨论了在对字符串列表进行排序时,sort()方法和sorted()函数是如何操作的。要了解更多关于字符串的内容,你可以阅读这篇关于字符串连接的文章。你可能也会喜欢列表理解上的这篇文章。
用 Python 对熊猫数据帧进行排序
原文:https://www.pythonforbeginners.com/basics/sort-pandas-dataframe-in-python
Pandas 数据帧用于在 Python 中处理表格数据。很多时候,我们需要根据列对数据帧进行排序。在本文中,我们将讨论在 Python 中对熊猫数据帧进行排序的不同方法。
sort_values()方法
sort_values()函数用于对一个熊猫数据帧进行水平或垂直排序。它具有以下语法。
DataFrame.sort_values(by, *, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)
这里,
by参数将一个字符串或一系列字符串作为其输入参数。by参数的输入取决于我们是否想要对数据帧的行或列进行排序。为了根据列对数据帧的行进行排序,我们可以将一个列名或列名列表传递给by参数。为了根据行对数据帧的列进行排序,我们可以将行索引或行索引列表传递给参数by。axis参数用于决定我们是否要对数据帧的行或列进行排序。为了根据一列或一组列对数据帧中的行进行排序,我们可以将值 0 传递给参数axis,这是它的默认值。为了根据一行或多行对数据帧的列进行排序,我们可以将值 1 传递给axis参数。ascending参数用于决定数据帧是按升序还是降序排序。默认情况下,True表示按升序排序。您可以将它设置为False,以降序对数据帧进行排序。如果排序是由多列完成的,您可以将一列True和False值传递给ascending参数,以决定数据帧是按升序还是降序排序。inplace参数用于决定我们是修改原始数据帧还是在排序后创建新的数据帧。默认情况下,inplace设置为False。因此,它不会修改原始数据帧,而sort_values()方法会返回新排序的数据帧。如果您想在排序时修改原始数据帧,可以将inplace设置为True。kind参数用于决定排序算法。默认情况下,sort_values()方法使用快速排序算法。经过数据分析,如果你认为输入的数据有一个确定的模式,某种排序算法可以减少时间,你可以使用‘mergesort’、‘heapsort’或‘stable’排序算法。na_position参数用于决定具有NaN值的行的位置。默认情况下,它的值为'last',表示具有NaN值的行最终存储在排序后的数据帧中。如果您想让带有NaN值的行位于排序数据帧的顶部,您可以将它设置为“first”。ignore_index参数用于决定输入数据帧中行的索引是否保留在排序数据帧中。默认情况下,True表示索引被保留。如果您想忽略初始数据帧的索引,您可以将ignore_index设置为True。key参数用于在排序前对数据帧的列执行操作。它将一个矢量化函数作为其输入参数。提供给key参数的函数必须将熊猫系列作为其输入参数,并返回熊猫系列。在排序之前,该函数独立应用于输入数据帧中的每一列。
执行后,如果 inplace 参数设置为False,则sort_values() 方法返回排序后的数据帧。如果inplace被设置为True,则sort_values()方法返回None。
Python 中按列对数据帧的行进行排序
为了按列对数据帧进行排序,我们将在数据帧上调用sort_values()方法。我们将把数据帧排序所依据的列名作为输入参数传递给“by”参数。执行后, sort_values()方法将返回排序后的数据帧。下面是我们在本文中用来创建数据帧的 CSV 文件。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
sorted_df=grades.sort_values(by="Marks")
print("The sorted dataframe is")
print(sorted_df)
输出:
The input 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
The sorted dataframe is
Class Roll Name Marks Grade
15 3 11 Bobby 50 D
4 1 15 Harry 55 C
8 2 27 Harsh 55 C
13 3 27 Aditya 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
9 2 23 Clara 78 B
12 3 15 Prashant 78 B
14 3 23 Radheshyam 78 B
7 2 15 Golu 79 B
10 3 33 Tina 82 A
0 1 11 Aditya 85 A
11 3 34 Amy 88 A
1 1 12 Chris 95 A
在上面的例子中,我们首先使用read_csv()函数将 CSV 文件读入数据帧。read_csv()函数获取 CSV 文件的文件名并返回一个数据帧。获得数据帧后,我们使用sort_values()方法通过"Marks"对其进行排序。
这里,sort_values() 返回一个新的排序数据帧。如果想对原始数据帧进行排序,可以使用如下所示的inplace=True参数。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
grades.sort_values(by="Marks",inplace=True)
print("The sorted dataframe is")
print(grades)
输出:
The input 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
The sorted dataframe is
Class Roll Name Marks Grade
15 3 11 Bobby 50 D
4 1 15 Harry 55 C
8 2 27 Harsh 55 C
13 3 27 Aditya 55 C
5 2 1 Joel 68 B
6 2 22 Tom 73 B
2 1 14 Sam 75 B
3 1 16 Aditya 78 B
9 2 23 Clara 78 B
12 3 15 Prashant 78 B
14 3 23 Radheshyam 78 B
7 2 15 Golu 79 B
10 3 33 Tina 82 A
0 1 11 Aditya 85 A
11 3 34 Amy 88 A
1 1 12 Chris 95 A
您可以观察到在将inplace设置为True后,原始数据帧已经被排序,
在上面的例子中,索引也随着行被混洗。这有时是不希望的。要通过刷新索引来更改行的索引,可以将ignore_index参数设置为True。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
grades.sort_values(by="Marks",inplace=True,ignore_index=True)
print("The sorted dataframe is")
print(grades)
输出:
The input 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
The sorted dataframe is
Class Roll Name Marks Grade
0 3 11 Bobby 50 D
1 1 15 Harry 55 C
2 2 27 Harsh 55 C
3 3 27 Aditya 55 C
4 2 1 Joel 68 B
5 2 22 Tom 73 B
6 1 14 Sam 75 B
7 1 16 Aditya 78 B
8 2 23 Clara 78 B
9 3 15 Prashant 78 B
10 3 23 Radheshyam 78 B
11 2 15 Golu 79 B
12 3 33 Tina 82 A
13 1 11 Aditya 85 A
14 3 34 Amy 88 A
15 1 12 Chris 95 A
在上面的示例中,您可以观察到每个位置的行索引与原始数据帧相同,并且没有与输入行混排。这是由于我们指定了ignore_index到True的原因。
按多列对数据帧的行进行排序
除了按一列对数据帧进行排序,我们还可以按多列对数据帧的行进行排序。
要按多列对 pandas 数据帧的行进行排序,可以将列名列表作为输入参数传递给“by”参数。当我们传递一个列名列表时,根据第一个元素对行进行排序。之后,根据列表的第二个元素对它们进行排序,以此类推。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
grades.sort_values(by=["Class","Marks"],inplace=True,ignore_index=True)
print("The sorted dataframe is")
print(grades)
输出:
The input 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
The sorted dataframe is
Class Roll Name Marks Grade
0 1 15 Harry 55 C
1 1 14 Sam 75 B
2 1 16 Aditya 78 B
3 1 11 Aditya 85 A
4 1 12 Chris 95 A
5 2 27 Harsh 55 C
6 2 1 Joel 68 B
7 2 22 Tom 73 B
8 2 23 Clara 78 B
9 2 15 Golu 79 B
10 3 11 Bobby 50 D
11 3 27 Aditya 55 C
12 3 15 Prashant 78 B
13 3 23 Radheshyam 78 B
14 3 33 Tina 82 A
15 3 34 Amy 88 A
在上面的例子中,我们按照两列对数据帧进行了排序,即Class和Marks。为此,我们将列表["Class", "Marks"] 传递给了sort_values()方法中的by参数。
这里,dataframe 按照by参数中列名的顺序排序。首先,dataframe 按"Class" 列排序。当两个或多个行在"Class"列中具有相同的值时,这些行将按"Marks" 列排序。
在熊猫数据帧中按降序排列值
默认情况下,sort_values() 方法按升序对数据帧进行排序。要按降序对值进行排序,可以使用“ascending”参数并将其设置为False。然后,sort_values() 方法将按降序对数据帧进行排序。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
grades.sort_values(by="Marks",inplace=True,ignore_index=True,ascending=False)
print("The sorted dataframe is")
print(grades)
输出:
The input 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
The sorted dataframe is
Class Roll Name Marks Grade
0 1 12 Chris 95 A
1 3 34 Amy 88 A
2 1 11 Aditya 85 A
3 3 33 Tina 82 A
4 2 15 Golu 79 B
5 1 16 Aditya 78 B
6 2 23 Clara 78 B
7 3 15 Prashant 78 B
8 3 23 Radheshyam 78 B
9 1 14 Sam 75 B
10 2 22 Tom 73 B
11 2 1 Joel 68 B
12 1 15 Harry 55 C
13 2 27 Harsh 55 C
14 3 27 Aditya 55 C
15 3 11 Bobby 50 D
在本例中,我们已经将ascending参数设置为False。因此,数据帧的行按Marks降序排列。
如果我们按多列对数据帧进行排序,也可以按降序对其进行排序,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
grades.sort_values(by=["Class","Marks"],inplace=True,ignore_index=True,ascending=False)
print("The sorted dataframe is")
print(grades)
输出:
The input 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
The sorted dataframe is
Class Roll Name Marks Grade
0 3 34 Amy 88 A
1 3 33 Tina 82 A
2 3 15 Prashant 78 B
3 3 23 Radheshyam 78 B
4 3 27 Aditya 55 C
5 3 11 Bobby 50 D
6 2 15 Golu 79 B
7 2 23 Clara 78 B
8 2 22 Tom 73 B
9 2 1 Joel 68 B
10 2 27 Harsh 55 C
11 1 12 Chris 95 A
12 1 11 Aditya 85 A
13 1 16 Aditya 78 B
14 1 14 Sam 75 B
15 1 15 Harry 55 C
在上面的例子中,dataframe 首先由Class列按降序排序。如果这些行对于Class列具有相同的值,则这些行按照Marks降序排序。
当按多列对数据帧进行排序时,您可以将一列True和False值传递给ascending参数。这有助于我们按照一列升序和另一列降序对数据帧进行排序。例如,考虑下面的例子。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
grades.sort_values(by=["Class","Marks"],inplace=True,ignore_index=True,ascending=[True,False])
print("The sorted dataframe is")
print(grades)
输出:
The input 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
The sorted dataframe is
Class Roll Name Marks Grade
0 1 12 Chris 95 A
1 1 11 Aditya 85 A
2 1 16 Aditya 78 B
3 1 14 Sam 75 B
4 1 15 Harry 55 C
5 2 15 Golu 79 B
6 2 23 Clara 78 B
7 2 22 Tom 73 B
8 2 1 Joel 68 B
9 2 27 Harsh 55 C
10 3 34 Amy 88 A
11 3 33 Tina 82 A
12 3 15 Prashant 78 B
13 3 23 Radheshyam 78 B
14 3 27 Aditya 55 C
15 3 11 Bobby 50 D
在本例中,我们按照Class和Marks列对数据帧进行了排序。在ascending参数中,我们给出了列表[True, False].,因此,数据帧首先由Class列按升序排序。如果这些行对于Class列具有相同的值,则这些行按照Marks降序排序。
在 Python 中使用 NaN 值对数据帧进行排序
在 python pandas 中,NaN值被视为浮点数。当我们使用sort_values()方法对包含NaN值的数据帧的行进行排序时,包含NaN值的行被放置在数据帧的底部,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
grades.sort_values(by="Marks",inplace=True,ignore_index=True)
print("The sorted dataframe is")
print(grades)
输出:
he input dataframe is
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris 95.0 A
2 1 14 Sam 75.0 B
3 1 16 Aditya 78.0 B
4 1 15 Harry NaN C
5 2 1 Joel 68.0 B
6 2 22 Tom 73.0 B
7 2 15 Golu 79.0 B
8 2 27 Harsh 55.0 C
9 2 23 Clara NaN B
10 3 33 Tina 82.0 A
11 3 34 Amy 88.0 A
12 3 15 Prashant NaN B
13 3 27 Aditya 55.0 C
14 3 23 Radheshyam 78.0 B
15 3 11 Bobby 50.0 D
The sorted dataframe is
Class Roll Name Marks Grade
0 3 11 Bobby 50.0 D
1 2 27 Harsh 55.0 C
2 3 27 Aditya 55.0 C
3 2 1 Joel 68.0 B
4 2 22 Tom 73.0 B
5 1 14 Sam 75.0 B
6 1 16 Aditya 78.0 B
7 3 23 Radheshyam 78.0 B
8 2 15 Golu 79.0 B
9 3 33 Tina 82.0 A
10 1 11 Aditya 85.0 A
11 3 34 Amy 88.0 A
12 1 12 Chris 95.0 A
13 1 15 Harry NaN C
14 2 23 Clara NaN B
15 3 15 Prashant NaN B
在这个例子中,您可以观察到Marks列包含一些NaN值。当我们按照Marks列对数据帧进行排序时,在Marks列中具有NaN值的行被放置在排序后的数据帧的底部。
如果您想将带有NaN值的行放在数据帧的顶部,您可以在如下所示的sort_values()函数中将na_position参数设置为“first” 。
import pandas as pd
grades=pd.read_csv("grade.csv")
print("The input dataframe is")
print(grades)
grades.sort_values(by="Marks",inplace=True,ignore_index=True,na_position="first")
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Class Roll Name Marks Grade
0 1 11 Aditya 85.0 A
1 1 12 Chris 95.0 A
2 1 14 Sam 75.0 B
3 1 16 Aditya 78.0 B
4 1 15 Harry NaN C
5 2 1 Joel 68.0 B
6 2 22 Tom 73.0 B
7 2 15 Golu 79.0 B
8 2 27 Harsh 55.0 C
9 2 23 Clara NaN B
10 3 33 Tina 82.0 A
11 3 34 Amy 88.0 A
12 3 15 Prashant NaN B
13 3 27 Aditya 55.0 C
14 3 23 Radheshyam 78.0 B
15 3 11 Bobby 50.0 D
The sorted dataframe is
Class Roll Name Marks Grade
0 1 15 Harry NaN C
1 2 23 Clara NaN B
2 3 15 Prashant NaN B
3 3 11 Bobby 50.0 D
4 2 27 Harsh 55.0 C
5 3 27 Aditya 55.0 C
6 2 1 Joel 68.0 B
7 2 22 Tom 73.0 B
8 1 14 Sam 75.0 B
9 1 16 Aditya 78.0 B
10 3 23 Radheshyam 78.0 B
11 2 15 Golu 79.0 B
12 3 33 Tina 82.0 A
13 1 11 Aditya 85.0 A
14 3 34 Amy 88.0 A
15 1 12 Chris 95.0 A
在上面的例子中,我们已经将参数na_position设置为"top"。因此,Marks列具有NaN值的行被放置在排序后的数据帧的顶部。
Python 中按行对数据帧的列进行排序
我们还可以根据行中的值对数据帧的列进行排序。为此,我们可以使用sort_values()函数中的axis参数。为了按行对数据帧的列进行排序,我们将把行的索引作为输入参数传递给“by”方法。此外,我们将在sort_values()方法中将axis参数设置为 1。执行后,sort_values() 方法将返回一个 dataframe,其中的列按给定的行排序。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("StudentMarks.csv",index_col="Student")
print("The input dataframe is")
print(grades)
grades.sort_values(by="Aditya",axis=1,inplace=True,ignore_index=True,na_position="first")
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Physics Chemistry Math Biology Arts
Student
Aditya 92 76 95 73 91
Chris 95 96 79 71 93
Sam 65 62 75 95 63
Harry 68 92 69 66 98
Golu 74 95 96 76 64
Joel 99 79 77 91 61
Tom 72 94 61 65 69
Harsh 98 99 93 95 91
Clara 93 67 78 79 71
Tina 99 76 78 94 95
The sorted dataframe is
0 1 2 3 4
Student
Aditya 73 76 91 92 95
Chris 71 96 93 95 79
Sam 95 62 63 65 75
Harry 66 92 98 68 69
Golu 76 95 64 74 96
Joel 91 79 61 99 77
Tom 65 94 69 72 61
Harsh 95 99 91 98 93
Clara 79 67 71 93 78
Tina 94 76 95 99 78
在上面的例子中,我们已经根据索引为"Aditya"的行对 dataframe 的列进行了排序。为此,我们将axis参数设置为 1,并将索引名传递给sort_values()方法的by参数。
在上面的输出数据帧中,您可以看到列名已经被删除。这是由于我们将ignore_index参数设置为True的原因。
如果您想保留列名,您可以删除参数ignore_index或将其设置为False,如下所示。
import pandas as pd
grades=pd.read_csv("StudentMarks.csv",index_col="Student")
print("The input dataframe is")
print(grades)
grades.sort_values(by="Aditya",axis=1,inplace=True,na_position="first")
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Physics Chemistry Math Biology Arts
Student
Aditya 92 76 95 73 91
Chris 95 96 79 71 93
Sam 65 62 75 95 63
Harry 68 92 69 66 98
Golu 74 95 96 76 64
Joel 99 79 77 91 61
Tom 72 94 61 65 69
Harsh 98 99 93 95 91
Clara 93 67 78 79 71
Tina 99 76 78 94 95
The sorted dataframe is
Biology Chemistry Arts Physics Math
Student
Aditya 73 76 91 92 95
Chris 71 96 93 95 79
Sam 95 62 63 65 75
Harry 66 92 98 68 69
Golu 76 95 64 74 96
Joel 91 79 61 99 77
Tom 65 94 69 72 61
Harsh 95 99 91 98 93
Clara 79 67 71 93 78
Tina 94 76 95 99 78
在本例中,您可以看到我们保留了数据帧的列名。这是因为我们移除了ignore_index参数,并将其设置为默认值False。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能还会喜欢这篇关于用 Python 对混合数据类型进行聚类的的文章。
sort index()方法
sort_index() 方法用于通过索引对熊猫数据帧进行排序。它具有以下语法。
DataFrame.sort_index(*, axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, ignore_index=False, key=None)
axis参数用于决定我们是否要对数据帧的行或列进行排序。为了根据一列或一组列对数据帧中的行进行排序,我们可以将值 0 传递给参数axis,这是它的默认值。为了根据一行或多行对数据帧的列进行排序,我们可以将值 1 传递给axis参数。level参数用于决定数据帧排序的索引级别。它有默认值None,表示所有索引级别都进行排序。如果希望按特定的索引级别对数据帧进行排序,可以将索引级别或索引名称传递给 level 参数。要按多个索引对数据帧进行排序,可以给level参数一个索引名或索引级别的列表。ascending参数决定数据帧是按升序还是降序排序。默认情况下,True表示按升序排序。您可以将它设置为False,以降序对数据帧进行排序。对于具有多级索引的数据帧,您可以传递一个由True和False值组成的列表,以决定您希望哪个级别按升序排列,哪个级别按降序排列。inplace参数用于决定我们是修改原始数据帧还是在排序后创建新的数据帧。默认情况下,inplace设置为False。因此,sort_index()方法不会修改原始数据帧,而是返回新排序的数据帧。如果您想在排序时修改原始数据帧,可以将inplace设置为True。kind参数用于决定排序算法。默认情况下,sort_values()方法使用快速排序算法。经过数据分析,如果你认为输入的数据有一个确定的模式,某种排序算法可以减少时间,你可以使用'mergesort’, ‘heapsort’,或‘stable’排序算法。na_position参数用于决定具有NaN值的行的位置。默认情况下,它的值为'last',表示具有NaN值的行最终存储在排序后的数据帧中。如果您想让带有NaN值的行位于排序数据帧的顶部,您可以将它设置为“first”。sort_remaining参数用于具有多级索引的数据帧。如果您想按未在level参数中指定的级别对数据帧进行排序,您可以将sort_remaining参数设置为True。如果您不想按剩余的索引对数据帧进行排序,您可以将sort_remaining设置为False。key参数用于在排序前对数据帧的索引执行操作。它接受一个矢量化函数作为其输入参数。提供给 key 参数的函数必须将一个 Index 对象作为其输入参数,并在执行后返回一个 Index 对象。在排序之前,该函数独立应用于输入数据帧中的每个索引列。
执行后,如果inplace参数设置为False,则sort_index() 方法返回排序后的数据帧。如果inplace被设置为True,则sort_index()方法返回None。
按索引排序熊猫数据帧
要按索引对 pandas 数据帧进行排序,可以在数据帧上使用sort_index()方法。为此,我们首先需要创建一个带有索引的数据帧。然后,我们可以调用 dataframe 上的sort_index() 方法。执行后,sort_index()方法返回一个排序后的数据帧。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col="Roll")
print("The input dataframe is")
print(grades)
sorted_df=grades.sort_index()
print("The sorted dataframe is")
print(sorted_df)
输出:
The input dataframe is
Class Name Marks Grade
Roll
11 1 Aditya 85.0 A
12 1 Chris 95.0 A
14 1 Sam 75.0 B
16 1 Aditya 78.0 B
15 1 Harry NaN C
1 2 Joel 68.0 B
22 2 Tom 73.0 B
15 2 Golu 79.0 B
27 2 Harsh 55.0 C
23 2 Clara NaN B
33 3 Tina 82.0 A
34 3 Amy 88.0 A
15 3 Prashant NaN B
27 3 Aditya 55.0 C
23 3 Radheshyam 78.0 B
11 3 Bobby 50.0 D
The sorted dataframe is
Class Name Marks Grade
Roll
1 2 Joel 68.0 B
11 1 Aditya 85.0 A
11 3 Bobby 50.0 D
12 1 Chris 95.0 A
14 1 Sam 75.0 B
15 1 Harry NaN C
15 2 Golu 79.0 B
15 3 Prashant NaN B
16 1 Aditya 78.0 B
22 2 Tom 73.0 B
23 2 Clara NaN B
23 3 Radheshyam 78.0 B
27 2 Harsh 55.0 C
27 3 Aditya 55.0 C
33 3 Tina 82.0 A
34 3 Amy 88.0 A
在上面的例子中,我们首先使用read_csv()方法读取一个 CSV 文件。在read_csv() 方法中,我们使用了index_col参数来指定"Roll" 列应该被用作数据帧的索引。当我们对由read_csv()方法返回的 dataframe 调用sort_index()方法时,它返回一个按索引列排序的 dataframe。
在上面的例子中,原始数据帧没有被修改。如果想修改原始数据帧,可以使用sort_index()方法中的inplace=True参数。执行后,原始数据帧将被修改。您可以在下面的示例中观察到这一点。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col="Roll")
print("The input dataframe is")
print(grades)
grades.sort_index(inplace=True)
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Class Name Marks Grade
Roll
11 1 Aditya 85.0 A
12 1 Chris 95.0 A
14 1 Sam 75.0 B
16 1 Aditya 78.0 B
15 1 Harry NaN C
1 2 Joel 68.0 B
22 2 Tom 73.0 B
15 2 Golu 79.0 B
27 2 Harsh 55.0 C
23 2 Clara NaN B
33 3 Tina 82.0 A
34 3 Amy 88.0 A
15 3 Prashant NaN B
27 3 Aditya 55.0 C
23 3 Radheshyam 78.0 B
11 3 Bobby 50.0 D
The sorted dataframe is
Class Name Marks Grade
Roll
1 2 Joel 68.0 B
11 1 Aditya 85.0 A
11 3 Bobby 50.0 D
12 1 Chris 95.0 A
14 1 Sam 75.0 B
15 1 Harry NaN C
15 2 Golu 79.0 B
15 3 Prashant NaN B
16 1 Aditya 78.0 B
22 2 Tom 73.0 B
23 2 Clara NaN B
23 3 Radheshyam 78.0 B
27 2 Harsh 55.0 C
27 3 Aditya 55.0 C
33 3 Tina 82.0 A
34 3 Amy 88.0 A
在本例中,您可以看到原始数据帧已经排序。这是因为我们在sort_index()方法中将inplace参数设置为True。
如果数据帧中有多级索引,并且希望按特定索引对数据帧进行排序,可以将索引级别传递给sort_index()方法中的level参数。
在下面的例子中,Class和Roll列都被用作索引。Class列用作主索引,而Roll列用作辅助索引。要仅通过Roll列对数据帧进行排序,我们将使用level参数并将其设置为 1。这样,输入数据帧将按Roll列排序。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col=["Class","Roll"])
print("The input dataframe is")
print(grades)
grades.sort_index(level=1,inplace=True)
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
16 Aditya 78.0 B
15 Harry NaN C
2 1 Joel 68.0 B
22 Tom 73.0 B
15 Golu 79.0 B
27 Harsh 55.0 C
23 Clara NaN B
3 33 Tina 82.0 A
34 Amy 88.0 A
15 Prashant NaN B
27 Aditya 55.0 C
23 Radheshyam 78.0 B
11 Bobby 50.0 D
The sorted dataframe is
Name Marks Grade
Class Roll
2 1 Joel 68.0 B
1 11 Aditya 85.0 A
3 11 Bobby 50.0 D
1 12 Chris 95.0 A
14 Sam 75.0 B
15 Harry NaN C
2 15 Golu 79.0 B
3 15 Prashant NaN B
1 16 Aditya 78.0 B
2 22 Tom 73.0 B
23 Clara NaN B
3 23 Radheshyam 78.0 B
2 27 Harsh 55.0 C
3 27 Aditya 55.0 C
33 Tina 82.0 A
34 Amy 88.0 A
在上面的例子中,我们使用索引级别作为level参数的输入参数。或者,您也可以将索引级别的名称传递给参数level,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col=["Class","Roll"])
print("The input dataframe is")
print(grades)
grades.sort_index(level="Roll",inplace=True)
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
16 Aditya 78.0 B
15 Harry NaN C
2 1 Joel 68.0 B
22 Tom 73.0 B
15 Golu 79.0 B
27 Harsh 55.0 C
23 Clara NaN B
3 33 Tina 82.0 A
34 Amy 88.0 A
15 Prashant NaN B
27 Aditya 55.0 C
23 Radheshyam 78.0 B
11 Bobby 50.0 D
The sorted dataframe is
Name Marks Grade
Class Roll
2 1 Joel 68.0 B
1 11 Aditya 85.0 A
3 11 Bobby 50.0 D
1 12 Chris 95.0 A
14 Sam 75.0 B
15 Harry NaN C
2 15 Golu 79.0 B
3 15 Prashant NaN B
1 16 Aditya 78.0 B
2 22 Tom 73.0 B
23 Clara NaN B
3 23 Radheshyam 78.0 B
2 27 Harsh 55.0 C
3 27 Aditya 55.0 C
33 Tina 82.0 A
34 Amy 88.0 A
在上面的例子中,我们使用参数level="Roll"而不是level=1 对输入数据帧进行排序。在这两种情况下,输出是相同的。
按照指定的索引排序后,sort_index() 方法还按照剩余的索引对数据帧进行排序。要停止这种情况,您可以将sort_remaining参数设置为False,如下例所示。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col=["Class","Roll"])
print("The input dataframe is")
print(grades)
grades.sort_index(level="Roll",inplace=True,sort_remaining=False)
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
16 Aditya 78.0 B
15 Harry NaN C
2 1 Joel 68.0 B
22 Tom 73.0 B
15 Golu 79.0 B
27 Harsh 55.0 C
23 Clara NaN B
3 33 Tina 82.0 A
34 Amy 88.0 A
15 Prashant NaN B
27 Aditya 55.0 C
23 Radheshyam 78.0 B
11 Bobby 50.0 D
The sorted dataframe is
Name Marks Grade
Class Roll
2 1 Joel 68.0 B
1 11 Aditya 85.0 A
3 11 Bobby 50.0 D
1 12 Chris 95.0 A
14 Sam 75.0 B
15 Harry NaN C
2 15 Golu 79.0 B
3 15 Prashant NaN B
1 16 Aditya 78.0 B
2 22 Tom 73.0 B
23 Clara NaN B
3 23 Radheshyam 78.0 B
2 27 Harsh 55.0 C
3 27 Aditya 55.0 C
33 Tina 82.0 A
34 Amy 88.0 A
在上面的例子中,如果两行在"Roll"列中有相同的值,并且sort_remaining参数没有设置为False,那么sort_index()方法将根据Class索引对数据帧进行排序。为了阻止sort_index()方法这样做,我们使用了sort_remaining参数并将其设置为False。
用 Python 对熊猫数据帧进行多索引排序
要通过多个索引对 pandas 数据帧进行排序,可以将索引级别列表传递给sort_index()方法的level参数,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col=["Class","Roll"])
print("The input dataframe is")
print(grades)
grades.sort_index(level=[0,1],inplace=True)
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
16 Aditya 78.0 B
15 Harry NaN C
2 1 Joel 68.0 B
22 Tom 73.0 B
15 Golu 79.0 B
27 Harsh 55.0 C
23 Clara NaN B
3 33 Tina 82.0 A
34 Amy 88.0 A
15 Prashant NaN B
27 Aditya 55.0 C
23 Radheshyam 78.0 B
11 Bobby 50.0 D
The sorted dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
15 Harry NaN C
16 Aditya 78.0 B
2 1 Joel 68.0 B
15 Golu 79.0 B
22 Tom 73.0 B
23 Clara NaN B
27 Harsh 55.0 C
3 11 Bobby 50.0 D
15 Prashant NaN B
23 Radheshyam 78.0 B
27 Aditya 55.0 C
33 Tina 82.0 A
34 Amy 88.0 A
在上面的例子中,我们将Class和Roll列作为索引。当我们通过level=[0,1]时,sort_index()方法首先通过Class列对输入数据帧进行排序。如果两行的Class列具有相同的值,它将根据Roll列对它们进行排序。
除了索引级别,您还可以将索引级别的名称传递给参数level,如下例所示。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col=["Class","Roll"])
print("The input dataframe is")
print(grades)
grades.sort_index(level=["Class","Roll"],inplace=True)
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
16 Aditya 78.0 B
15 Harry NaN C
2 1 Joel 68.0 B
22 Tom 73.0 B
15 Golu 79.0 B
27 Harsh 55.0 C
23 Clara NaN B
3 33 Tina 82.0 A
34 Amy 88.0 A
15 Prashant NaN B
27 Aditya 55.0 C
23 Radheshyam 78.0 B
11 Bobby 50.0 D
The sorted dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
15 Harry NaN C
16 Aditya 78.0 B
2 1 Joel 68.0 B
15 Golu 79.0 B
22 Tom 73.0 B
23 Clara NaN B
27 Harsh 55.0 C
3 11 Bobby 50.0 D
15 Prashant NaN B
23 Radheshyam 78.0 B
27 Aditya 55.0 C
33 Tina 82.0 A
34 Amy 88.0 A
在上面的例子中,我们使用参数level=["Class", "Roll"]而不是level=[0, 1]对输入数据帧进行排序。在这两种情况下,输出是相同的。
按索引降序排列熊猫数据帧
要按索引降序排列数据帧,可以将sort_index() 方法中的ascending参数设置为 False,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col=["Class","Roll"])
print("The input dataframe is")
print(grades)
grades.sort_index(level="Roll",inplace=True,ascending=False)
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
16 Aditya 78.0 B
15 Harry NaN C
2 1 Joel 68.0 B
22 Tom 73.0 B
15 Golu 79.0 B
27 Harsh 55.0 C
23 Clara NaN B
3 33 Tina 82.0 A
34 Amy 88.0 A
15 Prashant NaN B
27 Aditya 55.0 C
23 Radheshyam 78.0 B
11 Bobby 50.0 D
The sorted dataframe is
Name Marks Grade
Class Roll
3 34 Amy 88.0 A
33 Tina 82.0 A
27 Aditya 55.0 C
2 27 Harsh 55.0 C
3 23 Radheshyam 78.0 B
2 23 Clara NaN B
22 Tom 73.0 B
1 16 Aditya 78.0 B
3 15 Prashant NaN B
2 15 Golu 79.0 B
1 15 Harry NaN C
14 Sam 75.0 B
12 Chris 95.0 A
3 11 Bobby 50.0 D
1 11 Aditya 85.0 A
2 1 Joel 68.0 B
在上面的例子中,sort_index()方法按照Class和Roll列以降序对输入数据帧进行排序。
当通过多个索引对数据帧进行排序时,您可以将一列True和False值传递给ascending参数,如下所示。
import pandas as pd
grades=pd.read_csv("grade.csv",index_col=["Class","Roll"])
print("The input dataframe is")
print(grades)
grades.sort_index(level=["Class","Roll"],inplace=True,ascending=[False,True])
print("The sorted dataframe is")
print(grades)
输出:
The input dataframe is
Name Marks Grade
Class Roll
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
16 Aditya 78.0 B
15 Harry NaN C
2 1 Joel 68.0 B
22 Tom 73.0 B
15 Golu 79.0 B
27 Harsh 55.0 C
23 Clara NaN B
3 33 Tina 82.0 A
34 Amy 88.0 A
15 Prashant NaN B
27 Aditya 55.0 C
23 Radheshyam 78.0 B
11 Bobby 50.0 D
The sorted dataframe is
Name Marks Grade
Class Roll
3 11 Bobby 50.0 D
15 Prashant NaN B
23 Radheshyam 78.0 B
27 Aditya 55.0 C
33 Tina 82.0 A
34 Amy 88.0 A
2 1 Joel 68.0 B
15 Golu 79.0 B
22 Tom 73.0 B
23 Clara NaN B
27 Harsh 55.0 C
1 11 Aditya 85.0 A
12 Chris 95.0 A
14 Sam 75.0 B
15 Harry NaN C
16 Aditya 78.0 B
在本例中,我们按照Class和Marks列对数据帧进行了排序。在ascending参数中,我们已经给出了列表 [False, True]。因此,数据帧首先由Class列按descending顺序排序。如果这些行对于Class列具有相同的值,则这些行按Marks升序排序。
结论
在本文中,我们讨论了使用sort_values() 和 the sort_index() 方法在 Python 中对熊猫数据帧进行排序的不同方法。
要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的字典理解的文章。你可能也会喜欢这篇关于 python 中的列表理解的文章。
在 Python 中拆分字符串中的数字
原文:https://www.pythonforbeginners.com/python-strings/split-a-number-in-a-string-in-python
在处理文本数据时,可能需要从文本数据中提取数字。在 python 中,我们使用字符串处理文本数据。所以,我们要做的任务就是在一个字符串中找到并拆分一个数字。在提取数字时,我们可以将字符串分为两种类型。第一种类型将只包含空格分隔的数字,第二种类型的字符串也将包含字母和标点符号以及数字。在本文中,我们将看到如何从这两种类型的字符串中逐一提取数字。所以,让我们深入研究一下。
当字符串只包含空格分隔的数字时,拆分字符串中的数字。
当字符串格式中只包含空格分隔的数字时,我们可以简单地使用 python 字符串分割操作在空格处分割字符串。在任何字符串上调用 split 方法时,都会返回一个子字符串列表,在我们的例子中,这些子字符串是字符串格式的数字。在得到列表中字符串格式的数字后,我们可以使用int() 函数将所有的字符串转换成整数。这可以如下进行。
num_string="10 1 23 143 234 108 1117"
print("String of numbers is:")
print(num_string)
str_list=num_string.split()
print("List of numbers in string format is:")
print(str_list)
num_list=[]
for i in str_list:
num_list.append(int(i))
print("Output List of numbers is:")
print(num_list)
输出:
String of numbers is:
10 1 23 143 234 108 1117
List of numbers in string format is:
['10', '1', '23', '143', '234', '108', '1117']
Output List of numbers is:
[10, 1, 23, 143, 234, 108, 1117]
我们也可以如下使用列表理解执行上述操作。
num_string="10 1 23 143 234 108 1117"
print("String of numbers is:")
print(num_string)
str_list=num_string.split()
print("List of numbers in string format is:")
print(str_list)
num_list=[int(i) for i in str_list]
print("Output List of numbers is:")
print(num_list)
输出:
String of numbers is:
10 1 23 143 234 108 1117
List of numbers in string format is:
['10', '1', '23', '143', '234', '108', '1117']
Output List of numbers is:
[10, 1, 23, 143, 234, 108, 1117]
我们还可以使用map()函数将列表中的字符串转换成整数。map()函数将一个函数和一个 iterable 作为输入参数,对 iterable 对象的每个元素执行该函数,并返回可以转换为任何 iterable 的输出 map 对象。这里我们将提供 int()函数作为第一个参数,字符串列表作为第二个参数,这样字符串可以被转换成整数。这可以如下进行。
num_string="10 1 23 143 234 108 1117"
print("String of numbers is:")
print(num_string)
str_list=num_string.split()
print("List of numbers in string format is:")
print(str_list)
num_list=list(map(int,str_list))
print("Output List of numbers is:")
print(num_list)
输出:
String of numbers is:
10 1 23 143 234 108 1117
List of numbers in string format is:
['10', '1', '23', '143', '234', '108', '1117']
Output List of numbers is:
[10, 1, 23, 143, 234, 108, 1117]
当字符串包含字母时,拆分字符串中的数字。
当字符串包含字母时,我们将首先使用正则表达式从字符串中提取数字,然后将数字转换为整数形式。
为了提取数字,我们将使用来自re模块的 findall()方法。re.findall()将模式(在我们的例子中是一个或多个数字)和字符串作为输入,并返回与模式匹配的子字符串列表。提取字符串形式的数字列表后,我们可以将字符串转换为整数,如下所示。
import re
num_string="I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117"
print("Given String is:")
print(num_string)
pattern="\d+"
str_list=re.findall(pattern,num_string)
print("List of numbers in string format is:")
print(str_list)
num_list=[]
for i in str_list:
num_list.append(int(i))
print("Output List of numbers is:")
print(num_list)
输出:
Given String is:
I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117
List of numbers in string format is:
['20', '102', '23', '120', '1117']
Output List of numbers is:
[20, 102, 23, 120, 1117]
我们可以使用列表理解来执行上述操作,如下所示。
import re
num_string="I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117"
print("Given String is:")
print(num_string)
pattern="\d+"
str_list=re.findall(pattern,num_string)
print("List of numbers in string format is:")
print(str_list)
num_list=[int(i) for i in str_list]
print("Output List of numbers is:")
print(num_list)
输出:
Given String is:
I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117
List of numbers in string format is:
['20', '102', '23', '120', '1117']
Output List of numbers is:
[20, 102, 23, 120, 1117]
我们可以如下使用map()函数执行相同的操作。
import re
num_string="I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117"
print("Given String is:")
print(num_string)
pattern="\d+"
str_list=re.findall(pattern,num_string)
print("List of numbers in string format is:")
print(str_list)
num_list=list(map(int,str_list))
print("Output List of numbers is:")
print(num_list)
输出:
Given String is:
I have solved 20 ques102tions in last 23 days and have scored 120 marks with rank 1117
List of numbers in string format is:
['20', '102', '23', '120', '1117']
Output List of numbers is:
[20, 102, 23, 120, 1117]
结论
在本文中,我们看到了如何使用不同的方法,如列表理解和正则表达式,将一个字符串中的数字拆分并提取到另一个列表中。请继续关注更多内容丰富的文章。
在 Python 中拆分 Numpy 数组
原文:https://www.pythonforbeginners.com/basics/split-a-numpy-array-in-python
Numpy 数组是处理数字数据的最有效的数据结构之一。您可以使用内置函数对 numpy 数组执行不同的数学运算。在本文中,我们将讨论如何使用不同的函数在 Python 中分割 numpy 数组。
numpy 模块为我们提供了各种函数来将 Numpy 数组分割成不同的子数组。让我们逐一讨论。
使用 Split()函数拆分 numpy 数组
split()方法可用于根据索引将 numpy 数组分成相等的部分。它具有以下语法。
numpy.split(myArr, index_array_or_parts, axis)
这里,
- myArr 是我们必须拆分的数组。
- index_array_or_parts 确定如何将数组拆分成子数组。如果它是一个数值,数组被分成相等的部分。如果 index_array_or_parts 是索引数组,则子数组基于索引数组中的索引。
- 参数“轴”确定阵列拆分的轴。默认情况下,它的值为 0。您可以使用此参数来拆分二维数组。
- 为了理解 split()函数的工作原理,请考虑以下示例。
import numpy as np
myArr=np.arange(9)
print("The array is:")
print(myArr)
arr=np.split(myArr,3)
print("The split array is:")
print(arr)
输出:
The array is:
[0 1 2 3 4 5 6 7 8]
The split array is:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
在这里,我们将 myArr 分成 3 个相等的部分。您可以观察到 split()方法返回一个 numpy 数组,其中包含原始数组的子数组。
split()函数返回的子数组是原始数组的视图。因此,对 split()函数返回的子数组所做的任何更改都将反映在 myArr 中。
import numpy as np
myArr=np.arange(9)
print("The array is:")
print(myArr)
arr=np.split(myArr,3)
print("The split array is:")
print(arr)
arr[0][1]=999
print("The original arrays is:")
print(myArr)
输出:
The array is:
[0 1 2 3 4 5 6 7 8]
The split array is:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
The original arrays is:
[ 0 999 2 3 4 5 6 7 8]
在上面的例子中,您可以观察到我们对 split()方法返回的一个子数组进行了更改。但是,这种变化反映在原始数组中。这表明拆分的数组只是原始 numpy 数组的视图。
在将数组分割成相等的部分时,需要确保数值 index_array_or_parts 必须是数组长度的一个因子。否则,程序将遇到 ValueError 异常,并显示消息“数组拆分不会导致等分”。您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(9)
print("The arrays is:")
print(myArr)
arr=np.split(myArr,4)
print("The split array is:")
print(arr)
输出:
ValueError: array split does not result in an equal division
在上面的例子中,我们试图将一个包含 9 个元素的数组分成 4 部分。因此,程序会遇到 ValueError 异常。
您也可以在其索引处拆分数组。为此,您需要将一个索引数组传递给 split()函数,如以下语法所示。
numpy.split(myArr, [index1,index2,index3,….., indexN])
如果使用上面的语法,myArr 被分成不同的子数组。
- 第一个子数组由从索引 0 到索引 1-1 的元素组成。
- 第二子数组由从索引 index1 到索引 index2-1 的元素组成。
- 第三个子数组由从索引 index2 到索引 index3-1 的元素组成。
- 如果 indexN 小于数组的长度,则最后一个子数组由从索引 indexN-1 到最后一个元素的元素组成。
您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(12)
print("The array is:")
print(myArr)
arr=np.split(myArr,[1,4,7])
print("The split array is:")
print(arr)
输出:
The array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
The split array is:
[array([0]), array([1, 2, 3]), array([4, 5, 6]), array([ 7, 8, 9, 10, 11])]
在本例中,我们在索引 1、4 和 7 处拆分了输入数组。因此,第一子数组包含索引 0 处的元素,第二子数组包含从索引 1 到 3 的元素,第三子数组包含从索引 4 到 6 的元素,最后一个子数组包含从索引 7 到原始数组的最后一个元素的元素。
如果 indexN 大于数组的长度,您可以观察到最后的子数组将只是一个空的 numpy 数组。
import numpy as np
myArr=np.arange(12)
print("The array is:")
print(myArr)
arr=np.split(myArr,[1,4,11,14,17,20])
print("The split array is:")
print(arr)
输出:
The array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
The split array is:
[array([0]), array([1, 2, 3]), array([ 4, 5, 6, 7, 8, 9, 10]), array([11]), array([], dtype=int64), array([], dtype=int64), array([], dtype=int64)]
在本例中,我们尝试在索引 1、4、11、14、17 和 20 处拆分输入数组。由于数组只包含 12 个元素,split()方法返回的最后三个子数组是空的 numpy 数组。
将二维 numpy 数组垂直和水平分割成相等的部分
还可以使用 split()函数垂直拆分二维 numpy 数组。当我们将一个二维数组传递给 split()函数时,数组的行被分组为子数组。
例如,您可以将一个二维 numpy 数组拆分成行数相等的不同子数组,如下所示。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.split(myArr,3)
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26]]), array([[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53]]), array([[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]])]
在本例中,我们将形状为 9×9 的二维 numpy 数组垂直拆分为 3 个子数组。因此,split()方法返回一个包含 3 个形状为 3×9 的数组的数组。
这里,所需的子数组数量应该是原始数组中行数的一个因子。否则,split()方法将无法分割原始数组,程序会遇到 ValueError 异常。您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.split(myArr,4)
print("The split array is:")
print(arr)
输出:
ValueError: array split does not result in an equal division
这里,我们试图将一个有 9 行的数组分成 4 个子数组。因此,程序会遇到 ValueError 异常。
如果您想要水平分割一个二维数组,即沿着列,您可以在 split()方法中使用值为 1 的参数轴,如下所示。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.split(myArr,3, axis=1)
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20],
[27, 28, 29],
[36, 37, 38],
[45, 46, 47],
[54, 55, 56],
[63, 64, 65],
[72, 73, 74]]), array([[ 3, 4, 5],
[12, 13, 14],
[21, 22, 23],
[30, 31, 32],
[39, 40, 41],
[48, 49, 50],
[57, 58, 59],
[66, 67, 68],
[75, 76, 77]]), array([[ 6, 7, 8],
[15, 16, 17],
[24, 25, 26],
[33, 34, 35],
[42, 43, 44],
[51, 52, 53],
[60, 61, 62],
[69, 70, 71],
[78, 79, 80]])]
在本例中,我们将一个有 9 列的数组拆分为每个有 3 列的子数组。这里,所需子阵列的数量应该是列数的一个因子。否则,程序会遇到 ValueError 异常。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.split(myArr,4,axis=1)
print("The split array is:")
print(arr)
输出:
ValueError: array split does not result in an equal division
这里,我们试图将一个有 9 列的数组分割成 4 个子数组。因此,程序会遇到 ValueError 异常。
使用行和列索引拆分二维 numpy 数组
还可以使用下面的语法,根据 numpy 数组的行索引垂直拆分它们。
numpy.split(myArr, [rowindex1,rowindex2,rowindex3,….., rowindexN])
如果使用上面的语法,myArr 被垂直分割成不同的子数组。
- 第一个子数组由从行索引 0 到行索引 rowindex1-1 的行组成。
- 第二个子数组由从行索引 rowindex1 到行索引 rowindex2-1 的行组成。
- 第三个子数组由从行索引 rowindex2 到行索引 rowindex3-1 的行组成。
- 如果 indexN 小于数组中的行数,则最后一个子数组由从行索引 rowindexN-1 到最后一行的行组成。
您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.split(myArr,[2,5])
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17]]), array([[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44]]), array([[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]])]
在上面的例子中,我们在行索引 2 和 5 处分割了输入数组。因此,我们得到 3 个子数组。第一个子数组包含从开始到索引 1 的行。第二行子数组包含从索引 2 到索引 4 的行。最后一个子数组包含从索引 5 到最后的行。
如果 rowindexN 大于数组的长度,您可以看到最后一个子数组将只是一个空的 numpy 数组。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.split(myArr,[2,5,10,12,15])
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17]]), array([[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44]]), array([[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]]), array([], shape=(0, 9), dtype=int64), array([], shape=(0, 9), dtype=int64), array([], shape=(0, 9), dtype=int64)]
在上面的例子中,我们试图在行索引 2、5、10、12 和 15 处分割原始数组。然而,输入数组只有 9 行。因此,输出数组包含 3 个空的 numpy 数组。
要水平拆分 numpy 数组,即根据列索引对列进行分组,可以使用以下语法。
numpy.split(myArr, [columnindex1,columnindex2,columnindex3,….., columnindexN], axis=1)
如果使用上面的语法,myArr 被分成不同的子数组。
- 第一个子数组由从列索引 0 到列索引 columnindex1-1 的列组成。
- 第二个子数组由从列索引 columnindex1 到列索引 columnindex2-1 的列组成。
- 第三个子数组由从列索引 columnindex2 到列索引 columnindex3-1 的列组成。
- 如果 indexN 小于数组中的列数,则最后一个子数组由从列索引 columnindexN-1 到最后一行的列组成。
您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.split(myArr,[2,5],axis=1)
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1],
[ 9, 10],
[18, 19],
[27, 28],
[36, 37],
[45, 46],
[54, 55],
[63, 64],
[72, 73]]), array([[ 2, 3, 4],
[11, 12, 13],
[20, 21, 22],
[29, 30, 31],
[38, 39, 40],
[47, 48, 49],
[56, 57, 58],
[65, 66, 67],
[74, 75, 76]]), array([[ 5, 6, 7, 8],
[14, 15, 16, 17],
[23, 24, 25, 26],
[32, 33, 34, 35],
[41, 42, 43, 44],
[50, 51, 52, 53],
[59, 60, 61, 62],
[68, 69, 70, 71],
[77, 78, 79, 80]])]
在上面的例子中,我们在列索引 2 和 5 处分割了输入数组。因此,输出数组包含三个子数组。第一个子数组包含索引为 0 和 1 的列。第二子数组包含从索引 2 到 4 的列。最后一个子数组包含从索引 5 到最后一列的列。
如果 columnindexN 大于数组的长度,您可以看到最后一个子数组将只是一个空的 numpy 数组。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.split(myArr,[2,5,10,12,15],axis=1)
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1],
[ 9, 10],
[18, 19],
[27, 28],
[36, 37],
[45, 46],
[54, 55],
[63, 64],
[72, 73]]), array([[ 2, 3, 4],
[11, 12, 13],
[20, 21, 22],
[29, 30, 31],
[38, 39, 40],
[47, 48, 49],
[56, 57, 58],
[65, 66, 67],
[74, 75, 76]]), array([[ 5, 6, 7, 8],
[14, 15, 16, 17],
[23, 24, 25, 26],
[32, 33, 34, 35],
[41, 42, 43, 44],
[50, 51, 52, 53],
[59, 60, 61, 62],
[68, 69, 70, 71],
[77, 78, 79, 80]]), array([], shape=(9, 0), dtype=int64), array([], shape=(9, 0), dtype=int64), array([], shape=(9, 0), dtype=int64)]
在上面的示例中,我们尝试在列索引 2、5、10、12 和 15 处拆分原始数组。然而,输入数组只有 9 列。因此,输出数组包含 3 个空的 numpy 数组。
split()函数有一个缺点。当它无法将数组拆分为等长的子数组时,会引发 ValueError 异常。为了避免遇到 ValueError 异常,可以使用 array_split()函数。
使用 array_split()函数拆分 Numpy 数组
array_split()函数的工作方式与 split()函数相似。唯一的区别是,当它不能将数组拆分成相等的元素时,它不会引发 ValueError 异常。相反,对于应该分成 n 部分的长度为 l 的数组,它返回 l % n 个大小为 l//n + 1 的子数组,其余的大小为 l//n。
您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(12)
print("The array is:")
print(myArr)
arr=np.array_split(myArr,5)
print("The split array is:")
print(arr)
输出:
The array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
The split array is:
[array([0, 1, 2]), array([3, 4, 5]), array([6, 7]), array([8, 9]), array([10, 11])]
在上面的例子中,array_split()函数不能将输入数组分成 5 等份。但是,它不会引发 ValueError 异常。现在,array_split()函数返回 12%5,即大小为(12/5)+1 的 2 个子数组,即 3。其余子阵列的大小为 12//5,即 2。
在输出数组中,您可以看到有 2 个子数组,每个子数组有 3 个元素,还有 3 个子数组,每个子数组有 2 个元素。
还可以使用 array_split()函数沿行或列拆分二维数组,如下所示。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.array_split(myArr,4)
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26]]), array([[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44]]), array([[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62]]), array([[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]])]
在这个例子中,我们试图将一个 9 行的 numpy 数组垂直分割成 4 部分。因此,我们将得到 9%4,即 1 个大小为(9//4)+1 的子数组,即 3。其余子阵列的大小将为 9//4,即 2。
在输出数组中,您可以看到一个子数组包含三行,其余的子数组各包含两行。
使用 hsplit()函数拆分 Numpy 数组
函数的作用是:水平分割一个二维数组。要将一个二维数组拆分成列数相等的子数组,可以将原始数组和所需的子数组数传递给 hsplit()函数。执行后,它返回一个包含所有子数组的 numpy 数组,如下所示。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.hsplit(myArr,3)
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2],
[ 9, 10, 11],
[18, 19, 20],
[27, 28, 29],
[36, 37, 38],
[45, 46, 47],
[54, 55, 56],
[63, 64, 65],
[72, 73, 74]]), array([[ 3, 4, 5],
[12, 13, 14],
[21, 22, 23],
[30, 31, 32],
[39, 40, 41],
[48, 49, 50],
[57, 58, 59],
[66, 67, 68],
[75, 76, 77]]), array([[ 6, 7, 8],
[15, 16, 17],
[24, 25, 26],
[33, 34, 35],
[42, 43, 44],
[51, 52, 53],
[60, 61, 62],
[69, 70, 71],
[78, 79, 80]])]
在本例中,我们使用 hsplit()函数将一个 9×9 的数组分割成三个 9×3 形状的子数组。
如果原始数组中的列数不是所需子数组数的倍数,则 hsplit()函数将无法将原始数组平均分成多个子数组。在这种情况下,程序会遇到 ValueError 异常。您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.hsplit(myArr,4)
print("The split array is:")
print(arr)
输出:
ValueError: array split does not result in an equal division
在上面的例子中,我们试图将一个有 9 列的数组水平分割成 4 个子数组。因为 4 不是 9 的因子,所以 hsplit()函数不能平分数组,程序运行时出现 ValueError 异常。
要使用列索引水平拆分 numpy 数组,可以使用以下语法。
numpy.hsplit(myArr, [columnindex1,columnindex2,columnindex3,….., columnindexN])
如果使用上面的语法,myArr 被水平分割成不同的子数组。
- 第一个子数组由从列索引 0 到列索引 columnindex1-1 的列组成。
- 第二个子数组由从列索引 columnindex1 到列索引 columnindex2-1 的列组成。
- 第三个子数组由从列索引 columnindex2 到列索引 columnindex3-1 的列组成。
如果 indexN 小于数组中的列数,则最后一个子数组由从列索引 columnindexN-1 到最后一行的列组成。
您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.hsplit(myArr,[2,5,8])
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1],
[ 9, 10],
[18, 19],
[27, 28],
[36, 37],
[45, 46],
[54, 55],
[63, 64],
[72, 73]]), array([[ 2, 3, 4],
[11, 12, 13],
[20, 21, 22],
[29, 30, 31],
[38, 39, 40],
[47, 48, 49],
[56, 57, 58],
[65, 66, 67],
[74, 75, 76]]), array([[ 5, 6, 7],
[14, 15, 16],
[23, 24, 25],
[32, 33, 34],
[41, 42, 43],
[50, 51, 52],
[59, 60, 61],
[68, 69, 70],
[77, 78, 79]]), array([[ 8],
[17],
[26],
[35],
[44],
[53],
[62],
[71],
[80]])]
在本例中,我们在列索引 2、5 和 8 处拆分了一个包含 9 列的数组。因此,该阵列被分成 4 个子阵列。第一个子数组包含从索引 0 到 1 的列,第二个子数组包含从索引 2 到 4 的列,第三个子数组包含从索引 5 到 7 的列,第四个子数组包含原始数组中索引 8 处的列。
如果 columnindexN 大于数组的长度,您可以看到最后一个子数组将只是一个空的 numpy 数组。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The arrays is:")
print(myArr)
arr=np.hsplit(myArr,[2,5,8,12,20])
print("The split array is:")
print(arr)
输出:
The arrays is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1],
[ 9, 10],
[18, 19],
[27, 28],
[36, 37],
[45, 46],
[54, 55],
[63, 64],
[72, 73]]), array([[ 2, 3, 4],
[11, 12, 13],
[20, 21, 22],
[29, 30, 31],
[38, 39, 40],
[47, 48, 49],
[56, 57, 58],
[65, 66, 67],
[74, 75, 76]]), array([[ 5, 6, 7],
[14, 15, 16],
[23, 24, 25],
[32, 33, 34],
[41, 42, 43],
[50, 51, 52],
[59, 60, 61],
[68, 69, 70],
[77, 78, 79]]), array([[ 8],
[17],
[26],
[35],
[44],
[53],
[62],
[71],
[80]]), array([], shape=(9, 0), dtype=int64), array([], shape=(9, 0), dtype=int64)]
在上面的例子中,我们在索引 2、5、8、12 和 20 处分割了原始数组。因为输入数组只包含 9 列,所以输出数组包含两个空子数组。
本质上,hsplit()函数的工作方式与参数 axis=1 的 split()函数完全一样。
使用 vsplit()函数拆分数组
您可以使用 vsplit()函数垂直拆分 numpy 数组,即沿行拆分。要将二维数组拆分成行数相等的子数组,可以将原始数组和所需的子数组数传递给 vsplit()函数。执行后,它返回一个包含所有子数组的 numpy 数组,如下所示。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The array is:")
print(myArr)
arr=np.vsplit(myArr,3)
print("The split array is:")
print(arr)
输出:
The array is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26]]), array([[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53]]), array([[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]])]
在本例中,我们使用 vsplit()函数将一个 9×9 的数组垂直分割成三个大小为 3×9 的子数组。
如果原始数组中的行数不是所需子数组数的倍数,vsplit()函数将无法将原始数组平均划分为多个子数组。在这种情况下,程序会遇到 ValueError 异常。您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The array is:")
print(myArr)
arr=np.vsplit(myArr,4)
print("The split array is:")
print(arr)
输出:
ValueError: array split does not result in an equal division
在这个例子中,您可以观察到我们试图将一个 9 行的 numpy 数组垂直分割成 4 个子数组。由于 4 不是 9 的因子,vsplit()函数无法拆分原始值,程序运行时出现 ValueError 异常。
若要根据行索引垂直拆分二维 numpy 数组,可以使用以下语法。
numpy.vsplit(myArr, [rowindex1,rowindex2,rowindex3,….., rowindexN])
如果使用上面的语法,myArr 被垂直分割成不同的子数组。
- 第一个子数组由从行索引 0 到行索引 rowindex1-1 的行组成。
- 第二个子数组由从行索引 rowindex1 到行索引 rowindex2-1 的行组成。
- 第三个子数组由从行索引 rowindex2 到行索引 rowindex3-1 的行组成。
如果 indexN 小于数组中的行数,则最后一个子数组由从行索引 rowindexN-1 到最后一行的行组成。
您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The array is:")
print(myArr)
arr=np.vsplit(myArr,[2,5,8])
print("The split array is:")
print(arr)
输出:
The array is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17]]), array([[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44]]), array([[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71]]), array([[72, 73, 74, 75, 76, 77, 78, 79, 80]])]
在本例中,我们在第 2、5 和 8 行索引处垂直拆分了一个包含 9 行的数组。因此,该阵列被分成 4 个子阵列。第一个子数组包含从索引 0 到 1 的行,第二个子数组包含从索引 2 到 4 的行,第三个子数组包含从索引 5 到 7 的行,第四个子数组包含原始数组中索引 8 处的行。
如果 rowindexN 大于数组的长度,您可以看到最后一个子数组将只是一个空的 numpy 数组。
import numpy as np
myArr=np.arange(81).reshape((9,9))
print("The array is:")
print(myArr)
arr=np.vsplit(myArr,[2,5,8,12,20])
print("The split array is:")
print(arr)
输出:
The array is:
[[ 0 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16 17]
[18 19 20 21 22 23 24 25 26]
[27 28 29 30 31 32 33 34 35]
[36 37 38 39 40 41 42 43 44]
[45 46 47 48 49 50 51 52 53]
[54 55 56 57 58 59 60 61 62]
[63 64 65 66 67 68 69 70 71]
[72 73 74 75 76 77 78 79 80]]
The split array is:
[array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17]]), array([[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44]]), array([[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71]]), array([[72, 73, 74, 75, 76, 77, 78, 79, 80]]), array([], shape=(0, 9), dtype=int64), array([], shape=(0, 9), dtype=int64)]
在上面的例子中,我们在索引 2、5、8、12 和 20 处垂直分割了原始数组。因为输入数组只包含 9 列,所以输出数组包含两个空子数组。
vsplit()函数的工作方式类似于参数 axis=0 的 split()函数。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
在 Python 中沿深度分割三维数组
如果您有一个三维 numpy 数组,您可以使用 split()函数、array_split()函数或 split()函数沿深度拆分数组。
使用 Split()函数沿深度方向拆分三维数组
要将一个三维数组拆分成具有相同深度的子数组,可以将原始数组和所需子数组的数量传递给 split()或 array_split()函数,其中参数 axis=2。执行后,这些函数返回一个 numpy 数组,其中包含所有子数组,如下所示。
import numpy as np
myArr=np.arange(64).reshape((4,4,4))
print("The array is:")
print(myArr)
arr=np.split(myArr,2, axis=2)
print("The split array is:")
print(arr)
输出:
The array is:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[16 17 18 19]
[20 21 22 23]
[24 25 26 27]
[28 29 30 31]]
[[32 33 34 35]
[36 37 38 39]
[40 41 42 43]
[44 45 46 47]]
[[48 49 50 51]
[52 53 54 55]
[56 57 58 59]
[60 61 62 63]]]
The split array is:
[array([[[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]],
[[16, 17],
[20, 21],
[24, 25],
[28, 29]],
[[32, 33],
[36, 37],
[40, 41],
[44, 45]],
[[48, 49],
[52, 53],
[56, 57],
[60, 61]]]), array([[[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]],
[[18, 19],
[22, 23],
[26, 27],
[30, 31]],
[[34, 35],
[38, 39],
[42, 43],
[46, 47]],
[[50, 51],
[54, 55],
[58, 59],
[62, 63]]])]
在上面的示例中,我们将一个 4x4x4 的三维 numpy 数组沿深度方向拆分为两个 4x4x2 形状的数组。
如果原始数组的深度不是所需子数组数量的倍数,split()函数将无法将原始数组平均分成多个子数组。在这种情况下,程序会遇到 ValueError 异常。您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(64).reshape((4,4,4))
print("The array is:")
print(myArr)
arr=np.split(myArr,3, axis=2)
print("The split array is:")
print(arr)
输出:
ValueError: array split does not result in an equal division
在上面的例子中,我们试图将一个 4x4x4 的数组分成 3 部分。由于 3 不是 4 的因子,程序运行时遇到 ValueError 异常。
使用 array_split()函数沿深度方向拆分三维数组
当所需子数组的数量不是数组深度的一个因素时,array_split()函数不会抛出任何数组。array_split()函数将返回深度为(depth//number_of _sub-arrays)的深度为%number_of _sub-arrays 的数组,其余的子数组的深度为(depth//number_of _sub-arrays)。例如,考虑下面的例子。
import numpy as np
myArr=np.arange(64).reshape((4,4,4))
print("The array is:")
print(myArr)
arr=np.array_split(myArr,3, axis=2)
print("The split array is:")
print(arr)
输出:
The array is:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[16 17 18 19]
[20 21 22 23]
[24 25 26 27]
[28 29 30 31]]
[[32 33 34 35]
[36 37 38 39]
[40 41 42 43]
[44 45 46 47]]
[[48 49 50 51]
[52 53 54 55]
[56 57 58 59]
[60 61 62 63]]]
The split array is:
[array([[[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]],
[[16, 17],
[20, 21],
[24, 25],
[28, 29]],
[[32, 33],
[36, 37],
[40, 41],
[44, 45]],
[[48, 49],
[52, 53],
[56, 57],
[60, 61]]]), array([[[ 2],
[ 6],
[10],
[14]],
[[18],
[22],
[26],
[30]],
[[34],
[38],
[42],
[46]],
[[50],
[54],
[58],
[62]]]), array([[[ 3],
[ 7],
[11],
[15]],
[[19],
[23],
[27],
[31]],
[[35],
[39],
[43],
[47]],
[[51],
[55],
[59],
[63]]])]
在这里,我们尝试将一个 4x4x4 的数组在深度上分成 3 个部分。因此,输出数组包含 4%3,即 1 个深度为(4//3)+1,即 2 的子数组,其余子数组的深度为 4//3,即 1。
在输出中,您可以看到我们有一个 4x4x2 形状的子数组和两个 4x4x1 形状的子数组。
使用 dsplit()函数沿深度分割三维数组
除了 split()函数之外,还可以使用 dsplit()函数沿深度方向拆分 numpy 数组。为此,您只需将原始数组和所需子数组的数量传递给 dsplit()函数。执行后,dsplit()函数返回一个包含所有子数组的 numpy 数组。您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(64).reshape((4,4,4))
print("The array is:")
print(myArr)
arr=np.dsplit(myArr,2)
print("The split array is:")
print(arr)
输出:
The array is:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[16 17 18 19]
[20 21 22 23]
[24 25 26 27]
[28 29 30 31]]
[[32 33 34 35]
[36 37 38 39]
[40 41 42 43]
[44 45 46 47]]
[[48 49 50 51]
[52 53 54 55]
[56 57 58 59]
[60 61 62 63]]]
The split array is:
[array([[[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13]],
[[16, 17],
[20, 21],
[24, 25],
[28, 29]],
[[32, 33],
[36, 37],
[40, 41],
[44, 45]],
[[48, 49],
[52, 53],
[56, 57],
[60, 61]]]), array([[[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]],
[[18, 19],
[22, 23],
[26, 27],
[30, 31]],
[[34, 35],
[38, 39],
[42, 43],
[46, 47]],
[[50, 51],
[54, 55],
[58, 59],
[62, 63]]])]
在上面的示例中,我们使用 dsplit()函数将一个 4x4x4 的三维 numpy 数组沿深度方向拆分为两个 4x4x2 形状的数组。
如果原始数组的深度不是所需子数组数量的倍数,dsplit()函数将无法将原始数组平均分成多个子数组。在这种情况下,程序会遇到 ValueError 异常。您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(64).reshape((4,4,4))
print("The array is:")
print(myArr)
arr=np.dsplit(myArr,3)
print("The split array is:")
print(arr)
输出:
ValueError: array split does not result in an equal division
在上面的例子中,我们试图将一个 4x4x4 的数组分成 3 部分。由于 3 不是 4 的因子,程序运行时遇到 ValueError 异常。
要使用索引跨深度拆分三维 numpy 数组,可以使用以下语法。
numpy.dsplit(myArr, [depthindex1,depthindex2,depthindex3,….., depthindexN])
如果使用上面的语法,myArr 将在深度上被分割成不同的子数组。
- 第一子阵列由从深度索引 0 到深度索引 depthindex1-1 的元素组成。
- 第二子阵列由从深度索引 depthindex1 到深度索引 depthindex2-1 的元素组成。
- 第三个子阵列由从深度索引 depthindex2 到深度索引 depthindex3-1 的元素组成。
如果 depthindexN 小于数组中深度方向的元素数,则最后一个子数组由深度索引 depthindexN 到最后一行的元素组成。
您可以在下面的示例中观察到这一点。
import numpy as np
myArr=np.arange(64).reshape((4,4,4))
print("The array is:")
print(myArr)
arr=np.dsplit(myArr,[1,3])
print("The split array is:")
print(arr)
输出:
The array is:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[16 17 18 19]
[20 21 22 23]
[24 25 26 27]
[28 29 30 31]]
[[32 33 34 35]
[36 37 38 39]
[40 41 42 43]
[44 45 46 47]]
[[48 49 50 51]
[52 53 54 55]
[56 57 58 59]
[60 61 62 63]]]
The split array is:
[array([[[ 0],
[ 4],
[ 8],
[12]],
[[16],
[20],
[24],
[28]],
[[32],
[36],
[40],
[44]],
[[48],
[52],
[56],
[60]]]), array([[[ 1, 2],
[ 5, 6],
[ 9, 10],
[13, 14]],
[[17, 18],
[21, 22],
[25, 26],
[29, 30]],
[[33, 34],
[37, 38],
[41, 42],
[45, 46]],
[[49, 50],
[53, 54],
[57, 58],
[61, 62]]]), array([[[ 3],
[ 7],
[11],
[15]],
[[19],
[23],
[27],
[31]],
[[35],
[39],
[43],
[47]],
[[51],
[55],
[59],
[63]]])]
在上面的例子中,我们使用 dsplit()函数在深度索引 1 和 3 处分割输入数组。因此,输出中的第一个子数组包含直到索引 0 的元素,第二个子数组包含从深度索引 1 到深度索引 2 的元素。第三个子数组包含深度索引为 3 的元素。
您可以验证输出子数组的形状是(4,4,1)、(4,4,2)和(4,4,1)。
如果 depthindexN 大于深度上的元素数,您可以观察到最后的子数组将只是一个空的 numpy 数组,如下所示。
import numpy as np
myArr=np.arange(64).reshape((4,4,4))
print("The array is:")
print(myArr)
arr=np.dsplit(myArr,[1,3,5,8])
print("The split array is:")
print(arr)
输出:
The array is:
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[16 17 18 19]
[20 21 22 23]
[24 25 26 27]
[28 29 30 31]]
[[32 33 34 35]
[36 37 38 39]
[40 41 42 43]
[44 45 46 47]]
[[48 49 50 51]
[52 53 54 55]
[56 57 58 59]
[60 61 62 63]]]
The split array is:
[array([[[ 0],
[ 4],
[ 8],
[12]],
[[16],
[20],
[24],
[28]],
[[32],
[36],
[40],
[44]],
[[48],
[52],
[56],
[60]]]), array([[[ 1, 2],
[ 5, 6],
[ 9, 10],
[13, 14]],
[[17, 18],
[21, 22],
[25, 26],
[29, 30]],
[[33, 34],
[37, 38],
[41, 42],
[45, 46]],
[[49, 50],
[53, 54],
[57, 58],
[61, 62]]]), array([[[ 3],
[ 7],
[11],
[15]],
[[19],
[23],
[27],
[31]],
[[35],
[39],
[43],
[47]],
[[51],
[55],
[59],
[63]]]), array([], shape=(4, 4, 0), dtype=int64), array([], shape=(4, 4, 0), dtype=int64)]
在本例中,我们尝试在索引 1、3、5 和 8 处拆分输入数组。因为输入数组的深度为 4,所以输出数组包含两个空的 numpy 数组。
结论
在本文中,我们讨论了如何在 Python 中分割 numpy 数组。要了解更多关于数据帧和 numpy 数组的信息,您可以阅读这篇关于 pandas 数据帧索引的文章。您可能也会喜欢这篇关于用 Python 进行文本分析的文章。
在 Python 中将字符串拆分成字符
原文:https://www.pythonforbeginners.com/basics/split-a-string-into-characters-in-python
python 中使用字符串来处理文本数据。在本文中,我们将讨论在 Python 中将字符串拆分成字符的不同方法。
我们可以使用 Split()方法将一个字符串拆分成多个字符吗?
在 python 中,我们通常在一个字符串上使用split()方法将它拆分成子字符串。在字符串上调用split()方法时,它将一个字符作为分隔符作为输入参数。执行后,它在分隔符出现的所有情况下拆分字符串,并返回子字符串列表。例如,考虑下面的例子。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=myStr.split()
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: ['Python', 'For', 'Beginners']
有人会说我们可以用一个空字符串来把一个字符串分割成字符。让我们试试。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=myStr.split("")
print("The output is:",output)
输出:
ValueError: empty separator
在这个例子中,我们传递了一个空字符串作为分隔符,将字符串分割成字符。但是,程序会遇到 ValueError 异常,指出您使用了空分隔符。
因此,我们不能使用split()方法将 python 字符串分割成字符。让我们讨论一下其他的方法。
使用 Python 中的 for 循环将字符串分割成字符
python 中的字符串是可迭代的对象。因此,我们可以使用 for 循环逐个访问字符串的字符。
为了使用 for 循环分割字符串,我们将首先定义一个空列表来包含输出字符。然后,我们将使用一个 python for 循环遍历字符串的字符。迭代时,我们将使用append()方法将字符串的每个字符添加到列表中。当在列表上调用append()方法时,它将一个字符作为输入参数,并将其附加到列表的末尾。
在执行 for 循环后,我们将获得列表中字符串的所有字符。您可以在下面的示例中观察到这一点。
output=[]
myStr="Python For Beginners"
print("The input string is:",myStr)
for character in myStr:
output.append(character)
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: ['P', 'y', 't', 'h', 'o', 'n', ' ', 'F', 'o', 'r', ' ', 'B', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
在上面的例子中,我们将字符串"Python For Beginners" 分成了一系列字符。
使用列表理解将字符串转换为字符列表
列表理解用于从 python 中现有的 iterable 对象的元素创建一个列表。这是使用 for 循环和append()方法的更好的替代方法,因为我们可以用一条 python 语句将任何可迭代对象转换成一个列表。
您可以使用列表理解将一个字符串拆分成一个字符列表,如下所示。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=[character for character in myStr]
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: ['P', 'y', 't', 'h', 'o', 'n', ' ', 'F', 'o', 'r', ' ', 'B', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
在这个例子中,我们使用了列表理解而不是 for 循环。因此,我们能够用更少的代码行获得相同的结果。
使用 Python 中的 List()函数将字符串转换为字符列表
list() 构造函数用于从任何可迭代对象创建列表,比如 python 中的字符串、集合或元组。它将 iterable 对象作为其输入参数,并返回一个包含 iterable 对象元素的列表。
为了将字符串分解成字符,我们将把输入字符串传递给list()函数。执行后,它将返回一个包含输入字符串所有字符的列表。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=list(myStr)
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: ['P', 'y', 't', 'h', 'o', 'n', ' ', 'F', 'o', 'r', ' ', 'B', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's']
使用 tuple()函数
元组是列表的不可变版本。因此,您也可以将字符串转换为元组字符。为此,您可以使用tuple()功能。tuple()函数将 iterable 对象作为其输入参数,并返回一个包含 iterable 对象元素的元组。
为了分割一个字符串,我们将把输入字符串传递给 tuple()函数。执行后,它将返回一个包含输入字符串所有字符的元组。您可以在下面的示例中观察到这一点。
myStr="Python For Beginners"
print("The input string is:",myStr)
output=tuple(myStr)
print("The output is:",output)
输出:
The input string is: Python For Beginners
The output is: ('P', 'y', 't', 'h', 'o', 'n', ' ', 'F', 'o', 'r', ' ', 'B', 'e', 'g', 'i', 'n', 'n', 'e', 'r', 's')
结论
在本文中,我们讨论了在 python 中将字符串拆分成字符的不同方法。
要了解更多关于 python 编程的知识,你可以阅读这篇关于字符串操作的文章。您可能也会喜欢这篇关于 python simplehttpserver 的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
使用 Python 的 SSH 连接
原文:https://www.pythonforbeginners.com/code-snippets-source-code/ssh-connection-with-python
概观
上周,我写了一篇关于 Python 中的 pexpect 模块以及如何使用它来满足一些自动化需求的文章,比如 ssh 和 ftp。
我想继续这个话题,写一写它的 pxssh 类。有了 pxshmodule,就可以很容易地通过 ssh 访问其他服务器。本文基于这里找到的官方文档:http://pexpect.sourceforge.net/pxssh.html
pxssh 是什么?
Pxssh 基于 pexpect。它的类扩展了 pexpect.spawn 来专门设置 SSH 连接。我经常使用 pxssh 在 python 中建立 ssh 连接。
模块文档
打开一个终端,键入以下命令以获得关于该模块的帮助
import pxssh
help(pxssh)
Help on module pxssh:
NAME
pxssh
FILE
/usr/lib/python2.7/dist-packages/pxssh.py
DESCRIPTION
This class extends pexpect.spawn to specialize setting up SSH connections.
This adds methods for login, logout, and expecting the shell prompt.
$Id: pxssh.py 513 2008-02-09 18:26:13Z noah $
CLASSES
pexpect.ExceptionPexpect(exceptions.Exception)
ExceptionPxssh
pexpect.spawn(__builtin__.object)
pxssh
你也可以在这里看到帮助http://pexpect.sourceforge.net/pxssh.html
方法和登录过程
Pxssh 添加了登录、注销和期望 shell 提示符的方法。在 SSH 登录过程中,它会处理各种棘手的情况。
例如,如果会话是您的第一次登录,那么 pxssh 会自动接受远程证书;或者,如果您设置了公钥认证,那么 pxssh 不会等待密码提示。
pxssh 是如何工作的?
pxssh 使用 shell 提示符来同步远程主机的输出。为了使其更加健壮,它将 shell 提示符设置为比$或#更独特的东西。
这应该适用于大多数 Borne/Bash 或 Csh 风格的 shells。
例子
此示例在远程服务器上运行几个命令并打印结果。
首先,我们导入我们需要的模块。(pxssh 和 getpass)
我们导入了 getpass 模块,它会提示用户输入密码,而不会将用户输入的内容回显到控制台。
import pxssh
import getpass
try:
s = pxssh.pxssh()
hostname = raw_input('hostname: ')
username = raw_input('username: ')
password = getpass.getpass('password: ')
s.login (hostname, username, password)
s.sendline ('uptime') # run a command
s.prompt() # match the prompt
print s.before # print everything before the prompt.
s.sendline ('ls -l')
s.prompt()
print s.before
s.sendline ('df')
s.prompt()
print s.before
s.logout()
except pxssh.ExceptionPxssh, e:
print "pxssh failed on login."
print str(e)
在远程 SSH 服务器上运行命令
让我们再举一个例子。要运行一个命令(“uptime”)并打印输出,您需要像这样做:
import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
print "SSH session failed on login."
print str(s)
else:
print "SSH session login successful"
s.sendline ('uptime')
s.prompt() # match the prompt
print s.before # print everything before the prompt.
s.logout()
#We can also execute multiple command like this:
s.sendline ('uptime;df -h')
关于 pxssh 的更多信息,请参见官方文档
在 Python 中堆叠和连接 Numpy 数组
原文:https://www.pythonforbeginners.com/basics/stack-and-concatenate-numpy-arrays-in-python
Numpy 数组是数字数据最有效的数据结构之一。您可以使用内置函数对 numpy 数组执行不同的数学运算。本文将讨论如何在 Python 中使用不同的函数连接 numpy 数组。
Concatenate()函数
您可以使用 concatenate()函数沿现有轴连接一维和二维 numpy 数组。它具有以下语法。
np.concatenate((arr1,arr2,…,arrN),axis=0)
这里,concatenate()函数将一组 numpy 数组作为它的第一个输入参数。执行后,它返回连接的数组。
- 使用 axis 参数确定连接输入数组的轴。它的默认值为 0。
- 对于轴=0,不同阵列的行垂直连接,即不同阵列的行成为输出阵列的行。
- 对于轴=1,数组水平连接,即输入数组的列成为输出数组的列。
- 对于 axis=None,所有输入数组都被展平,输出是一维 numpy 数组。
使用 Python 中的 Concatenate()函数连接一维数组
您可以使用 concatenate()函数连接一维 numpy 数组,方法是将包含 numpy 数组的元组作为输入参数传递,如下所示。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,8)
print("Second array is:")
print(arr2)
arr3=np.concatenate([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[5 6 7]
Concatenated array is:
[0 1 2 3 4 5 6 7]
这里,我们水平连接了两个 numpy 数组。因此,输入数组的所有元素都被转换为输出数组的元素。
不能使用 concatenate()函数和 axis=1 参数垂直连接一维 numpy 数组。这样做会导致 numpy。AxisError 异常,显示消息“numpy。AxisError:轴 1 超出了 1 维数组的界限。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,8)
print("Second array is:")
print(arr2)
arr3=np.concatenate([arr1,arr2],axis=1)
print("Concatenated array is:")
print(arr3)
输出:
AxisError: axis 1 is out of bounds for array of dimension 1
在这里,您可以观察到我们试图使用 concatenate()函数垂直连接 numpy 数组,这导致了 AxisError 异常。
使用 Python 中的 Concatenate()函数连接二维数组
我们可以使用 concatenate()函数水平和垂直连接二维数组。
要水平连接 numpy 数组,可以将数组元组作为第一个输入参数,将 axis=1 作为第二个输入参数传递给 concatenate()函数。执行后,concatenate()函数将返回一个 numpy 数组,如下所示。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.concatenate([arr1,arr2],axis=1)
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[ 0 1 2 3 4 15 16 17 18 19]
[ 5 6 7 8 9 20 21 22 23 24]
[10 11 12 13 14 25 26 27 28 29]]
在上面的例子中,我们水平连接了二维数组。您可以观察到,输入数组的行被组合起来创建输出数组的行。
在水平连接 numpy 数组时,需要确保所有输入数组都有相同的行数。水平串联具有不同行数的数组将导致 ValueError 异常,并显示消息“ValueError:串联轴的所有输入数组维度必须完全匹配”。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,35).reshape(4,5)
print("Second array is:")
print(arr2)
arr3=np.concatenate([arr1,arr2],axis=1)
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 3 and the array at index 1 has size 4
在上面的例子中,我们试图连接 3 行和 4 行的数组。因为输入数组具有不同的行数,所以程序会遇到 ValueError 异常。
还可以使用 concatenate()函数垂直连接 numpy 数组。为此,您需要将参数 axis=0 作为输入与数组元组一起传递。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.concatenate([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
在本例中,我们垂直连接了二维 numpy 数组。您可以观察到输入数组的列被组合在一起,以创建输出数组的列。
在垂直连接 numpy 数组时,您需要确保所有输入数组都有相同数量的列。否则,程序将遇到 ValueError 异常,并显示消息“ValueError:串联轴的所有输入数组维数必须完全匹配”。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,36).reshape(3,7)
print("Second array is:")
print(arr2)
arr3=np.concatenate([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 7
在这个例子中,我们试图连接两个分别有 5 列和 7 列的数组。由于列数不同,程序在连接数组时遇到 ValueError 异常。
您也可以连接所有二维 numpy 数组来创建一维数组。为此,您必须将参数 axis=None 与数组元组一起传递给 concatenate()函数。在这种情况下,所有输入数组首先被展平为一维数组。之后,它们被连接起来。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,36).reshape(3,7)
print("Second array is:")
print(arr2)
arr3=np.concatenate([arr1,arr2],axis=None)
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19 20 21]
[22 23 24 25 26 27 28]
[29 30 31 32 33 34 35]]
Concatenated array is:
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
24 25 26 27 28 29 30 31 32 33 34 35]
在这个例子中,我们在连接二维数组后创建了一个一维数组。您可以观察到输入二维数组的元素以行主顺序包含在输出数组中。
concatenate()函数沿现有轴组合输入数组。因此,组合二维数组只能得到二维数组作为输出。如果希望堆叠 numpy 数组以形成数据立方体类型的结构,则不能使用 concatenate()函数来实现。为此,我们将使用 stack()函数。
使用 Python 中的 hstack()函数连接 Numpy 数组
hstack()函数的工作方式类似于参数 axis=1 的 concatenate()函数。当我们将数组元组传递给 hstack()函数时,它会水平堆叠输入数组的列,并返回一个新数组。对于一维输入数组,它返回一维数组,如下所示。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,8)
print("Second array is:")
print(arr2)
arr3=np.hstack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[5 6 7]
Concatenated array is:
[0 1 2 3 4 5 6 7]
在这里,您可以观察到输入数组被连接起来形成一个输出一维数组。输入数组的元素包含在输出数组中的顺序与它们作为 hstack()函数的输入的顺序相同。
对于二维数组输入,hstack()函数返回一个二维数组,如下所示。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.hstack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[ 0 1 2 3 4 15 16 17 18 19]
[ 5 6 7 8 9 20 21 22 23 24]
[10 11 12 13 14 25 26 27 28 29]]
在上面的例子中,输入数组的行已经被组合以创建输出数组的行。
在使用具有 hstack()函数的二维数组时,需要确保输入数组具有相等的行数。否则,您将得到一个 ValueError 异常,并显示消息“ValueError:串联轴的所有输入数组维度必须完全匹配”。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,35).reshape(4,5)
print("Second array is:")
print(arr2)
arr3=np.hstack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 3 and the array at index 1 has size 4
在上面的例子中,我们试图使用 hstack()函数连接两个行数不同的二维数组。因此,程序会遇到 ValueError 异常。因此,我们可以说 hstack()函数的工作方式类似于参数 axis=1 的 concatenate()函数。
使用 Python 中的 vstack()函数连接 Numpy 数组
不能使用 concatenate()函数垂直连接 numpy 数组。但是,您可以使用 vstack()函数垂直连接一维数组来创建二维 numpy 数组。当我们将 1 维 numpy 数组的元组或列表传递给 vstack()函数时,它返回一个 2 维数组,其中所有输入的 numpy 数组都被转换为行。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,10)
print("Second array is:")
print(arr2)
arr3=np.vstack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[5 6 7 8 9]
Concatenated array is:
[[0 1 2 3 4]
[5 6 7 8 9]]
在本例中,我们将两个一维数组垂直连接在一起,创建了一个二维数组。使用 concatenate()函数不可能做到这一点。
使用 vstack()函数连接一维 numpy 数组时,需要确保所有数组的长度相等。否则,程序将遇到 ValueError 异常,如下例所示。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,8)
print("Second array is:")
print(arr2)
arr3=np.vstack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 3
在这里,您可以观察到我们试图连接两个长度分别为 5 和 3 的数组。因此,程序会遇到 ValueError 异常。
还可以使用 vstack()函数垂直连接二维 numpy 数组。在这种情况下,vstack()函数的工作方式类似于参数 axis=0 的 concatenate()函数。
当我们将一个 2-D numpy 数组的列表或元组传递给 vstack()函数时,我们得到一个 2-D 数组作为输出。输入数组的行被转换为输出 numpy 数组的行。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.vstack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
在本例中,您可以看到我们使用 vstack()函数垂直连接了两个二维数组。在这里,输入数组的列组合起来创建输出数组的列。
在使用带有 vstack()函数的二维数组时,需要确保输入数组具有相等的列数。否则,您将得到一个 ValueError 异常,并显示消息“ValueError:串联轴的所有输入数组维度必须完全匹配”。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,36).reshape(3,7)
print("Second array is:")
print(arr2)
arr3=np.vstack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 7
在这个例子中,我们试图连接两个分别有 5 列和 7 列的数组。因此,程序会遇到 ValueError 异常。
对于 vstack()函数,您可以观察到它的行为与 concatenate()函数不同。对于一维数组,concatenate()函数的工作方式与 concatenate()函数不同。但是,对于二维数组,vstack()函数的工作方式与 concatenate()函数类似。
使用 Stack()函数堆叠数组
stack()函数可用于使用 N 维数组创建 N+1 维数组。例如,您可以使用 stack()函数从二维数组创建三维数组,或者从一维数组创建二维数组。
stack()函数将一组输入数组作为它的第一个输入参数,并将我们用来堆叠数组的轴作为它的第二个输入参数。
使用 Python 中的 Stack()函数堆叠一维数组
您可以使用 stack()函数跨行和列堆叠一维数组。要跨行堆叠一维数组,可以传递参数 axis=0 和输入数组元组,如下所示。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,10)
print("Second array is:")
print(arr2)
arr3=np.stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[5 6 7 8 9]
Concatenated array is:
[[0 1 2 3 4]
[5 6 7 8 9]]
在本例中,我们使用 stack()函数垂直堆叠了两个一维数组,以创建一个二维数组。这里,输入数组被转换成输出数组的行。
还可以使用 stack()函数跨列堆叠两个一维数组。为此,您需要将参数 axis=1 和输入数组元组一起传递给 stack()函数。在输出中,您将获得一个二维数组,其中输入数组被转换为输出数组的列。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,10)
print("Second array is:")
print(arr2)
arr3=np.stack([arr1,arr2],axis=1)
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[5 6 7 8 9]
Concatenated array is:
[[0 5]
[1 6]
[2 7]
[3 8]
[4 9]]
在上面的例子中,您可以观察到我们堆叠了两个一维 numpy 数组来创建一个二维数组。这里,一维输入数组被转换成二维数组的列。
使用 stack()函数只能堆叠长度相等的一维 numpy 数组。否则,程序将遇到 ValueError 异常,并显示消息“ValueError:所有输入数组必须具有相同的形状”。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,15)
print("Second array is:")
print(arr2)
arr3=np.stack([arr1,arr2],axis=1)
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all input arrays must have the same shape
在上面的例子中,我们试图水平堆叠两个一维数组。因为数组的长度不同,程序会遇到 ValueError 异常,指出所有输入数组的形状必须相同。
使用 Python 中的 Stack()函数堆叠二维数组
您可以使用 stack()函数跨行、列和深度堆叠二维数组。
要跨长度堆叠两个 numpy 数组,我们可以将 axis=0 和输入数组元组一起传递给 stack()函数。如果输入元组中有 K 个形状为 MxN 的输入数组,则输出数组的形状将为 KxMxN。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.stack([arr1,arr2],axis=0)
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]]
在本例中,我们使用 stack()函数堆叠了两个形状为 3×5 的 numpy 数组。得到的数组是 2x3x5 的形状。因此,在使用 stack()函数堆叠二维数组后,我们得到了三维数组。
要跨宽度堆叠 numpy 数组,可以将 axis=1 与输入数组元组一起传递给 stack()函数。如果输入元组中有 K 个形状为 MxN 的输入数组,则输出数组的形状将为 MxKxN。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.stack([arr1,arr2],axis=1)
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[[ 0 1 2 3 4]
[15 16 17 18 19]]
[[ 5 6 7 8 9]
[20 21 22 23 24]]
[[10 11 12 13 14]
[25 26 27 28 29]]]
在本例中,您可以看到我们得到了形状为 3x2x5 的输出数组。因此,stack()函数在参数 axis=1 的情况下执行时,会在宽度方向上堆叠输入数组。
为了在深度上堆叠 numpy 数组,我们可以将 axis=2 和输入数组的元组一起传递给 stack()函数。如果输入元组中有 K 个形状为 MxN 的输入数组,则输出数组的形状将为 MxNxK。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.stack([arr1,arr2],axis=2)
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[[ 0 15]
[ 1 16]
[ 2 17]
[ 3 18]
[ 4 19]]
[[ 5 20]
[ 6 21]
[ 7 22]
[ 8 23]
[ 9 24]]
[[10 25]
[11 26]
[12 27]
[13 28]
[14 29]]]
在本例中,我们在深度方向上堆叠了 2 个形状为 3×5 的数组后,得到了形状为 3x5x2 的输出数组。
您应该记住,传递给输入元组中的 stack()函数的输入数组应该具有相同的形状。否则,程序将遇到 ValueError 异常。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,35).reshape(4,5)
print("Second array is:")
print(arr2)
arr3=np.stack([arr1,arr2],axis=2)
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all input arrays must have the same shape
在上面的例子中,我们将不同形状的输入数组传递给了 stack()函数。因此,该函数会引发 ValueError 异常。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
使用 Python 中的 column_stack()函数堆栈 Numpy 数组
numpy 模块为我们提供了 column_stack()函数来将一维数组作为二维数组的列进行堆叠。当我们将一个一维数组的列表或元组传递给 column_stack()函数时,它返回一个二维数组,其中包含作为其列的输入一维数组。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,10)
print("Second array is:")
print(arr2)
arr3=np.column_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[5 6 7 8 9]
Concatenated array is:
[[0 5]
[1 6]
[2 7]
[3 8]
[4 9]]
在这里,所有的输入一维数组都被堆叠成输出数组的列。我们可以说 column_stack()函数的工作方式类似于 axis=1 的 stack()函数。
传递给 column_stack()函数的一维数组必须具有相等的长度。否则,程序将会出错。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,12)
print("Second array is:")
print(arr2)
arr3=np.column_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 5 and the array at index 1 has size 7
这里,我们尝试使用 column_stack()函数分别堆叠大小为 5 和 7 的两个数组。因此,该函数会引发 ValueError 异常。
还可以使用 column_stack()函数水平堆叠二维数组,如下所示。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.column_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[ 0 1 2 3 4 15 16 17 18 19]
[ 5 6 7 8 9 20 21 22 23 24]
[10 11 12 13 14 25 26 27 28 29]]
当我们使用 column_stack()函数堆叠二维数组时,输入数组的行被组合起来以创建输出数组的行。因此,该函数的工作方式类似于 axis=1 时的 hstack()函数或 vstack()函数。
当使用 column_stack()函数堆叠二维数组时,需要确保每个输入数组中的行数相同。否则,程序将会遇到如下所示的 ValueError 异常。
import numpy as np
arr1=np.arange(15).reshape((3,5))
print("First array is:")
print(arr1)
arr2=np.arange(15,35).reshape(4,5)
print("Second array is:")
print(arr2)
arr3=np.column_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 3 and the array at index 1 has size 4
还可以使用 column_stack()函数将一维和二维数组作为新数组的列进行堆叠,如下所示。
import numpy as np
arr1=np.arange(3)
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.column_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[ 0 15 16 17 18 19]
[ 1 20 21 22 23 24]
[ 2 25 26 27 28 29]]
在这里,您可以看到一维数组和二维数组的列构成了输出数组的列。同样,一维数组的长度和二维数组的行数应该相同,这一点很重要。否则,程序将会遇到如下所示的异常。
import numpy as np
arr1=np.arange(4)
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.column_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 4 and the array at index 1 has size 3
使用 Python 中的 row_stack()函数堆栈 Numpy 数组
numpy 模块为我们提供了 row_stack()函数来将一维数组作为二维数组的行进行堆栈。当我们将一个一维数组的列表或元组传递给 row_stack()函数时,它返回一个二维数组,其中包含作为其行的输入一维数组。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,10)
print("Second array is:")
print(arr2)
arr3=np.row_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[5 6 7 8 9]
Concatenated array is:
[[0 1 2 3 4]
[5 6 7 8 9]]
在上面的例子中,我们堆叠了两个长度为 5 的一维数组,以创建一个大小为 2×5 的二维数组。通过观察输出,我们可以说 row_stack()函数的工作方式类似于 vstack()函数。
传递给 row_stack()函数的一维数组必须具有相等的长度。否则,程序将会出错。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,11)
print("Second array is:")
print(arr2)
arr3=np.row_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 6
还可以使用 row_stack()函数垂直堆叠二维数组,如下所示。
import numpy as np
arr1=np.arange(15).reshape(3,5)
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.row_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
在这个例子中,我们使用 row_stack()函数垂直堆叠了两个二维数组。您可以观察到输入数组的列已经被组合在一起,以创建输出数组的列。
当使用 row_stack()函数堆叠二维数组时,需要确保每个输入数组中的列数是相同的。否则,程序将会遇到如下所示的 ValueError 异常。
import numpy as np
arr1=np.arange(15).reshape(3,5)
print("First array is:")
print(arr1)
arr2=np.arange(15,33).reshape(3,6)
print("Second array is:")
print(arr2)
arr3=np.row_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 6
您还可以使用 row_stack()函数将一维和二维数组堆叠为新数组的行,如下所示。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.row_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[ 0 1 2 3 4]
[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
在这里,您可以看到一维数组和二维数组的列构成了输出数组的行。同样,一维数组的长度和输入二维数组中的列数应该相同,这一点很重要。否则,程序将会遇到如下所示的异常。
import numpy as np
arr1=np.arange(6)
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.row_stack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 6 and the array at index 1 has size 5
使用 dstack()函数跨深度堆叠 Numpy 数组
函数的作用是:在深度上堆叠 numpy 数组。当我们将一个一维数组的列表或元组传递给 dstack()函数时,它会返回一个三维数组,如下所示。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,10)
print("Second array is:")
print(arr2)
arr3=np.arange(11,16)
print("Third array is:")
print(arr3)
arr4=np.dstack([arr1,arr2,arr3])
print("Concatenated array is:")
print(arr4)
输出:
First array is:
[0 1 2 3 4]
Second array is:
[5 6 7 8 9]
Third array is:
[11 12 13 14 15]
Concatenated array is:
[[[ 0 5 11]
[ 1 6 12]
[ 2 7 13]
[ 3 8 14]
[ 4 9 15]]]
如果给定 K 个长度为 N 的一维数组作为 dstack()函数的输入,则输出数组的形状为 1xNxK。
作为 dstack()函数的输入给出的一维数组的长度应该相同。如果输入数组的长度不同,程序会遇到如下所示的 ValueError 异常。
import numpy as np
arr1=np.arange(5)
print("First array is:")
print(arr1)
arr2=np.arange(5,11)
print("Second array is:")
print(arr2)
arr3=np.arange(11,16)
print("Third array is:")
print(arr3)
arr4=np.dstack([arr1,arr2,arr3])
print("Concatenated array is:")
print(arr4)
输出:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 5 and the array at index 1 has size 6
对于二维数组,dstack()函数的工作方式类似于参数 axis=2 的 stack()函数。如果输入元组中有 K 个形状为 MxN 的输入数组,则输出数组的形状将为 MxNxK。您可以在下面的示例中观察到这一点。
import numpy as np
arr1=np.arange(15).reshape(3,5)
print("First array is:")
print(arr1)
arr2=np.arange(15,30).reshape(3,5)
print("Second array is:")
print(arr2)
arr3=np.dstack([arr1,arr2])
print("Concatenated array is:")
print(arr3)
输出:
First array is:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Second array is:
[[15 16 17 18 19]
[20 21 22 23 24]
[25 26 27 28 29]]
Concatenated array is:
[[[ 0 15]
[ 1 16]
[ 2 17]
[ 3 18]
[ 4 19]]
[[ 5 20]
[ 6 21]
[ 7 22]
[ 8 23]
[ 9 24]]
[[10 25]
[11 26]
[12 27]
[13 28]
[14 29]]]
在本例中,我们在深度方向上堆叠了两个形状为 3×5 的二维阵列。输出数组的形状为 3x5x2。因此,我们可以说 dstack()函数作为参数 axis=2 的 stack()函数工作。
结论
在本文中,我们讨论了如何在 Python 中连接 1 维和 2 维 NumPy 数组。我们还讨论了如何水平、垂直和横向堆叠 1-D 和 2-D numpy 数组。
要了解更多关于数据帧和 numpy 数组的信息,您可以阅读这篇关于 pandas 数据帧索引的文章。您可能也会喜欢这篇关于用 Python 进行文本分析的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
Python 中的堆栈
原文:https://www.pythonforbeginners.com/data-types/stack-in-python
在 python 中,有内置的数据结构,如列表、元组、集合和字典,但我们可能需要 python 程序中的一些附加功能。例如,如果我们的程序需要后进先出(LIFO)功能,那么没有内置的数据结构提供这种功能。我们可以使用堆栈来实现 python 中的后进先出功能。在本文中,我们将研究堆栈数据结构背后的概念,并用 python 实现它。
什么是堆栈?
堆栈是一种线性数据结构,在这种结构中,我们只能访问或删除最后添加到堆栈中的元素。在现实生活中,我们可以以一叠盘子为例,我们只能取出最上面的盘子,因为它是最后添加的。我们可以在 python 中对堆栈数据结构执行以下操作。
- 插入元素(推动元素)
- 移除元素(弹出元素)
- 检查堆栈是否为空
- 检查堆栈中最顶端的元素
- 检查堆栈的大小
在接下来的小节中,我们将实现 stack 和它的所有部分,并将在 python 中实现它们。
如何在 python 中实现 stack?
在本教程中,我们将定义一个名为 Stack 的类,并使用 python 列表实现该堆栈。在 Stack 类中,我们将有一个包含添加到堆栈中的数据的列表和一个存储堆栈大小的变量。所有操作,如 push、pop、检查堆栈的大小、检查堆栈的最顶端元素以及检查堆栈是否为空,都将在恒定时间内执行,因此时间复杂度为 O(1)。堆栈类将被定义如下。stackList 被初始化为空列表,stackSize 被初始化为 0。
class Stack:
def __init__(self):
self.stackList=[]
self.stackSize=0
在 python 中将项目推入堆栈
要将一个项目插入堆栈,也就是将一个元素推入堆栈,我们只需将该元素添加到列表中,然后将 stackSize 变量递增 1。为了实现该操作,我们定义了一个方法,该方法将元素作为参数,并将元素添加到堆栈中的列表中。然后它递增 stackSize 变量。下面是 push()方法的实现。
def push(self,item):
self.stackList.append(item)
self.stackSize+=1
用 python 从堆栈中弹出项目
要从堆栈中移除一个项目,即从堆栈中弹出一个元素,我们必须从堆栈中移除最后添加到它的元素。当我们在推操作时将元素添加到堆栈中的列表时,列表中的最后一个元素将是最近的元素,并将从堆栈中移除。所以我们只需从列表中删除最后一个元素。
为了实现 pop 操作,我们将实现 pop()方法,该方法首先检查堆栈中元素的数量是否大于 0。如果是,那么它将从列表中删除最后一个元素,并将 stackSize 减 1。如果堆栈中的元素数为 0,它将显示一条错误消息,说明列表为空。对于这个任务,我们将使用异常处理,使用 python try except 在堆栈大小为 0 时引发异常。pop()方法可以按如下方式实现。
def pop(self):
try:
if self.stackSize==0:
raise Exception("Stack is Empty, returning None")
temp=self.stackList.pop()
self.stackSize-=1
return temp
except Exception as e:
print(str(e))
检查堆栈的大小
要检查堆栈的大小,我们只需检查 stackSize 变量的值。对于这个操作,我们将实现 size()方法,该方法返回 stackSize 变量的值,如下所示。
def size(self):
return self.stackSize
检查堆栈是否为空
要检查堆栈是否没有元素,即它是否为空,我们必须检查 stackSize 变量是否为 0。对于这个操作,我们将实现 isEmpty()方法,如果 stackSize 变量为 0,则返回 True,否则返回 false。下面是 isEmpty()方法的实现。
def isEmpty(self):
if self.stackSize==0:
return True
else:
return False
检查堆栈的最顶层元素
堆栈最顶端的元素将是最近添加到其中的元素。要检查栈顶的元素,我们只需返回栈中列表的最后一个元素。对于这个操作,我们将实现 top()方法,它首先检查堆栈是否为空,即 stackSize 是否为 0,如果是,它将打印一条消息,说明堆栈为空。否则它将返回列表的最后一个元素。这可以如下实现。
def top(self):
try:
if self.stackSize==0:
raise Exception("Stack is Empty, returning None")
return self.stackList[-1]
except Exception as e:
print(str(e))
下面是用 python 实现 stack 的完整工作代码。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 19:38:55 2021
@author: aditya1117
"""
class Stack:
def __init__(self):
self.stackList=[]
self.stackSize=0
def push(self,item):
self.stackList.append(item)
self.stackSize+=1
def pop(self):
try:
if self.stackSize==0:
raise Exception("Stack is Empty, returning None")
temp=self.stackList.pop()
self.stackSize-=1
return temp
except Exception as e:
print(str(e))
def size(self):
return self.stackSize
def isEmpty(self):
if self.stackSize==0:
return True
else:
return False
def top(self):
try:
if self.stackSize==0:
raise Exception("Stack is Empty, returning None")
return self.stackList[-1]
except Exception as e:
print(str(e))
#Execution
s=Stack()
#push element
s.push(1)
#push element
s.push(2)
#push element
s.push(3)
print("popped element is:")
print(s.pop())
#push an element
s.push(4)
print("topmost element is:")
print(s.top())
输出:
popped element is:
3
topmost element is:
4
结论
在本文中,我们研究并实现了 python 中的栈数据结构。我们已经看到了堆栈的操作,您可能会发现它与 python dictionary ,list,set e.t.c .非常不同。堆栈广泛用于现实世界的应用程序中,如表达式处理、回溯、函数调用和许多其他操作,您应该对此有所了解。请继续关注更多内容丰富的文章。
Python 标准库与 Python 包索引
原文:https://www.pythonforbeginners.com/modules-in-python/standard-library-vs-package-index
Python 模块
在这篇文章中,我们将看看 Python 标准库和 Python 包索引
Python 标准库
网址:http://docs.python.org/library/index.html
是什么:
系统中已经存在的模块的集合,因此不需要安装它们。只需导入您想要使用的模块。搜索模块:http://docs.python.org/py-modindex.html
Python 包索引
URL:http://pipi . python . org/pipi
是什么:
它是一个软件仓库,包含社区成员创建的 2400 多个软件包。
Python 字符串串联和格式化
原文:https://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python
任何语言都需要完成的一个常见任务是合并或组合字符串。这个过程被称为连接。
描述它的最好方式是,你把两个独立的字符串——由解释器存储——合并成一个。
例如,一个字符串是“hello”,另一个是“world”当你使用串联来组合它们时,它就变成了一个字符串,或者“hello world”。
这篇文章将描述如何在 Python 中连接字符串。有不同的方法可以做到这一点,我们将讨论最常见的方法。之后,我们将探索格式化,以及它是如何工作的。
串联
在 Python 中,有几种方法可以连接或组合字符串。创建的新字符串被称为字符串对象。显然,这是因为 Python 中的一切都是对象——这就是为什么 Python 是一种面向对象的语言。
为了将两个字符串合并成一个对象,可以使用“+”运算符。编写代码时,应该是这样的:
*str1 = “Hello”*
*str2 = “World”*
*str1 + str2*
这段代码的最后一行是连接,当解释器执行它时,将创建一个新的字符串。
需要注意的一点是,Python 不能连接字符串和整数。这被认为是两种不同类型的对象。所以,如果你想合并两者,你需要把整数转换成字符串。
以下示例显示了当您尝试合并 string 和 integer 对象时会发生什么。它是从大卫·鲍尔的个人网站上复制过来的。
*>>> print ‘red’ + ‘yellow’*
*Redyellow*
*>>> print ‘red’ * 3*
*Redredred*
*>>> print ‘red’ + 3*
*Traceback* *(most recent call last):*
*File “”, line 1, in*
*TypeError**: cannot concatenate ‘**str**’ and ‘**int**’ objects*
*>>>*
作为参考,“> > >”字符表示解释器请求命令的位置。
请注意,将字符串“red”乘以三次会得出值“redred”。这很重要,所以一定要记下来。
此外,我们可以看到,当试图结合'红色'和 3 解释抛出了一个错误。这是我们试图连接一个字符串和整数对象的地方,但是失败了。
通俗地说,字符串可以是任何记录的字符,但它最常用于存储单词和信息。另一方面,整数是没有小数点的记录数值。Python 不能将单词和数字相加。从这个角度来看,错误发生的原因是有道理的。
为了实现这一点,我们可以使用适当的函数将数字转换成字符串。其代码应该是这样的:
*>>> print ‘red’ +* *str**(**3)*
*red3*
*>>>*
我们使用的方法是 str ( ) 函数。注意解释器是如何简单地将两个对象组合起来,并在被要求打印数据时将它们吐出来的?
Python 中的字符串格式
在 Python 中,我们可以利用两种不同的字符串插值方法。
字符串插值是一个术语,用于描述对包含在一个或多个占位符中的字符串值进行求值的过程。简而言之,它帮助开发者进行字符串格式化和连接。
希望您自己更熟悉这个术语,因为它是任何编程语言的关键元素,尤其是 Python。
使用%运算符的字符串格式
在我们深入了解之前,理解% string 运算符在 Python 3.1 及更高版本中将被弃用(不再使用)是很重要的。最终,它将从该语言的未来版本中完全删除。
然而,熟悉这种方法仍然是一个好主意,也是常见的做法。
理解如何使用操作符的最好方法是查看活动代码。
*x* *= ‘apple**s**’*
*y* *= ‘lemon**s**’*
*z* *= “**In* *the basket are %s and %s” % (**x,y**)*
此示例代码将按照我们设置的顺序,用相应的字符串替换“%s”运算符值。当您打印“z”字符串对象时——在执行上述代码后——它将返回以下内容:
*In the basket are apples and lemons*
用{ }运算符设置字符串格式
当您使用花括号或 {} 操作符时,它们充当您希望存储在字符串中的变量的占位符。为了将变量传递给字符串,你必须调用 格式( ) 方法。
使用()**格式的一个好处是,您不必在连接数据之前将整数转换成字符串。它会自动为你做到这一点。这就是为什么它是首选运算符方法的一个原因。
再一次,让我们来看一些展示这一点的代码:
*Fname* *= “John”*
*Lname* *= “Doe”*
*Age = “24”*
*p**rint “{} {} is {} years* *old.“* *format(**fname**,* *lname**, age)*
这样做的目的是获取适当的值,并将它们作为变量存储在相应的字符串中。
格式( ) 方法的另一个有用的特性是,您实际上不必按照您希望变量显示的顺序将输入提供给解释器,只要您像这样对占位符进行编号:
*print “{0} {1} is {2} years old.”* *format(**fname**,* *lname**, age)*
在 Python 中使用 Join 方法
Python 中的 join 方法用于连接字符串列表。
例如
*>>>* *‘* *‘* *.join([‘the’, ‘quick’, ‘brown’, ‘fox’, ‘jumps’, ‘over’, ‘the’, ‘lazy’, ‘dog’])*
*‘the quick brown fox jumps over the lazy dog’*
让我们创建一个新的名单,其中包括一些伟大的乐队,但这一次让我们做不同的事情。
*>>> music = [“Metallica”, “Rolling Stones”, “ACDC”, “Black Sabbath”, “**Shinedown**”]*
这个代码片段将使用我们指定的变量创建一个名为“music”的字符串或列表。
您可以通过加入一个空格来加入新列表,如下所示:
*>>> print* *‘ ’**.join(music)*
您也可以通过在新的一行开始代码来加入它,如:
*>>> print “*
*“.join**(music)*
方法没有对错,用你喜欢的方法。
相关职位
字符串串联和格式化
原文:https://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting
作为一名 Python 程序员,几乎可以保证你需要掌握字符串连接和格式化。
无论是准备一条最终将被用户阅读的消息,还是编写供内部使用的工具,知道如何构造完美的字符串对于几乎任何程序的成功都是至关重要的。
沟通往往是成功的关键。在一个由数据驱动的世界里尤其如此。
幸运的是,Python 为我们提供了一系列简化字符串格式化过程的工具。掌握这些工具将提供精确制作琴弦所需的技能。
发展您的 Python 技能将使您能够处理大量的数据,以及 Python 提供的所有令人兴奋的机会。
串联
在任何编程语言中,连接两个或多个字符串都是一项常见的任务。这样做被称为串联。Python 提供了几个连接字符串的工具。
当我们在 Python 中连接字符串时,两个或更多的字符串被组合成一个新的字符串。这有点像数学中的“加法”,但我们添加的不是数字,而是字符串。
在 Python 中连接字符串最简单的方法是使用'+'操作符。在 Python 中,'+'操作符将连接任意两个字符串。
下面是语法:
final_string = string_one + string_two
当我们以这种方式“添加”字符串时,我们实际上是在连接它们。正如您所看到的,Python 几乎从字面上理解了添加字符串的概念。
让我们通过一个代码示例来看看'+'操作符的工作情况。
示例 Python 中的串联
# joining strings with the '+' operator
# first create two strings that we’ll combine
first_name = "Sherlock"
last_name = "Holmes"
# join the names, separated by a space character
full_name = first_name + " " + last_name
print("Hello, " + full_name + ".")
输出
Hello, Sherlock Holmes.
在本 Python 示例中,使用“+”运算符连接三个字符串,并将它们的值组合成一个新的字符串。
使用'+'操作符是 Python 中组合字符串的一种直接方法。
在创建了变量 full_name 之后,我们的程序使用 print()方法在命令提示符中显示字符串。使用'+'操作符,我们格式化字符串以包含正确的标点符号,并添加额外的空格。
使用“+”操作符连接字符串是创建更易读文本的一种很好的方式。创建人类可读的文本是软件设计的一个重要部分。当字符串格式正确且含义清晰时,软件使用起来就容易多了。
可以使用更长的 Python 语句连接多个字符串。
示例 2:组合多个字符串。
act1 = "This is the beginning"
act2 = "this is the middle"
act3 = "this is the end"
story = act1 + ", " + act2 + ", and " + act3 + "."
print(story)
输出
This is the beginning, this is the middle, and this is the end.
从上面的例子可以看出,可以连接的字符串数量没有限制。通过使用'+'操作符,可以连接许多不同的字符串。
需要注意的是,Python 不能连接不同类型的对象。例如,不可能将一个字符串和一个数字连接起来。这样做会引起 Python 的抱怨。
>>> str = "red"
>>> print(str + 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
尝试连接字符串和整数会导致错误。从 Traceback 消息中可以看出,Python 只能将一个字符串与另一个字符串连接起来。
解决这个问题的一个简单方法是使用 str() 方法。使用这个方法会将一个数字转换成一个字符串。
>>> print("red" + " " + str(13))
red 13
str() 方法简化了将不同类型的数据转换成字符串对象的过程。这是一种特殊的 Python 方法,适用于许多不同类型的对象。使用它可以快速将数字、小数和其他对象转换为字符串。
示例 3:使用 str()方法将数字转换为字符串。
# use the str() method to convert numbers to strings
num = 221
letter = "B"
street = "Baker Street"
print(str(num) + letter + " " + street)
输出
221B Baker Street
Python 中的字符串格式
为了精确地格式化文本,有必要使用更高级的技术。有时我们想在字符串中插入一个变量而不使用连接。这可以通过一种叫做插值的方法来实现。
通过插值,Python 动态地将数据插入到字符串中。Python 提供了多种插值数据的方法。
这些方法非常灵活,并且根据您的需要,可以与其他工具结合使用。使用它们精确格式化字符串并提高 Python 程序的可读性。
使用%运算符的字符串格式
在 Python 中格式化字符串的一种方法是使用“%”运算符。使用“%”操作符将文本插入到占位符中,其方式类似于 format() 方法的工作方式。
当用“%”操作符格式化字符串时,我们必须指定将替换占位符的数据类型。这可以通过特殊字符来实现。
例如,“s”字符用于告诉 Python 我们想要用字符串数据替换占位符。
建议阅读:如果你对机器学习感兴趣,可以阅读这篇关于机器学习中回归的文章。您可能也会喜欢这篇关于带有数字示例的 k 均值聚类的文章。
示例 4:使用%运算符对数据进行插值。
# %s for strings
# %d for numbers
print("%s never ends, %s." % ("Education","Watson"))
输出
Education never ends, Watson.
如果我们想用其他数据类型替换占位符,我们需要使用其他特殊字符。例如,您可以使用“%d”作为字符串中的占位符,将整数传递给字符串 buying。
author = "Arthor Conan Doyle"
bday = 1859
print("%s was born on %d." % (author, bday))
用{ }运算符设置字符串格式
格式化复杂的字符串可能很繁琐。为了减轻负担,Python 提供了一种将数据插入字符串的特殊方法。
使用 format() 方法,占位符用于将数据插入到字符串中。 format() 方法将在字符串中查找这些占位符,并用新值替换它们,作为参数提供给该方法。
占位符是用花括号指定的。
我们来看看 format() 方法在起作用。
示例 5:使用。format()替换字符串中的文本。
subject = "Dr. Watson"
clues = 3
message = "{}, I've found {} clues!".format(subject, clues)
print(message)
输出
Dr. Watson, I've found 3 clues!
在 Python 中使用 Join 方法
还可以使用命名索引来标识占位符。
join() 方法用于连接一个 Python iterable。该方法提供了一种将列表或字典转换为字符串数据的快速方法。
这个方法是一个强大而通用的工具,可用于处理字符串数据的列表或字典。
打印 Python 列表的内容是一项常见的任务。使用 join() 方法,可以将字符串列表转换成单个字符串。 join() 方法需要一个连接符,它是用来将列表“粘合”在一起的字符。
例如,如果使用逗号作为连接符,那么列表中的元素将在最后的字符串中用逗号分隔。任何字符串都可以作为连接符,但是通常使用空格这样的东西来分隔字符串。
示例 6:用 join()方法连接字符串。
# create a list of string data
titles = ["A Study in Scarlet", "The Sign of Four", "A Scandal in Bohemia"]
# join the list using a comma and a space to separate the strings
print(', '.join(titles))
输出
A Study in Scarlet, The Sign of Four, A Scandal in Bohemia
join() 方法也可以用来打印字典的内容。
示例 7:字典和 join()方法。
# use join() to print the characters in the dictionary
print(' '.join(characters))
# populate a list of occupations
occupations = []
for character in characters:
occupations.append(characters[character])
# use join to print the occupations
print(' '.join(occupations))
输出
Sherlock Watson Moriarty
在这个例子中,我们使用了 join() 方法来打印字典和列表。如您所见,如果使用 join() 来打印字典,那么只打印字典的键。
为了查看字典中的值,创建并填充一个新列表是很有用的。这个新列表将保存字典中分配给键的值。
创建并填充一个名为“职业”的新列表后,我们可以使用 join() 来打印该列表。
Detective Doctor Criminal Mastermind
相关职位
学习正确格式化字符串是每个 Python 程序员都需要的一项重要技能。Python 提供了几个工具来完成这项任务。掌握这些工具将确保你的程序尽可能清晰和有用。
有几种方法可以提高你在这方面的技能。最简单的方法是练习你新发现的 Python 技能,并构建一些你自己的程序。例如,构建一个基于文本的游戏是练习字符串连接和格式化的绝佳方式。
学生可以使用其他资源。如果您对 Python 编程的更多信息感兴趣,请访问下面的链接。
Python 中的字符串索引
原文:https://www.pythonforbeginners.com/strings/string-indexing-in-python
在 Python 中,字符串用于处理文本数据。在处理字符串时,我们经常需要访问字符串的某一部分。在本文中,我们将看到如何使用 Python 中的索引来提取字符串的各个部分。
什么是字符串索引?
如果我们有一个有序序列或容器对象,如字符串、列表或元组,我们可以使用它们在序列中的相对位置来访问对象的元素。有序序列中元素的相对位置称为索引。通过索引,我们可以使用索引访问有序序列中的任何元素。
在 python 中,字符串索引是从零开始的。这意味着我们从 0 开始计数,字符串的第一个字符被赋予索引 0,第二个字符被赋予索引 1,第三个字符被赋予索引 2,依此类推。
我们可以通过下面的例子来理解这一点。
假设我们有一个字符串“PythonForBeginners”
这里,字母“P”的索引是 0。字母“y”的索引是 1。字母“t”的索引是 2,字母“h”的索引是 3,依此类推。最后一个字母“s”的索引是 17。
在 python 中,我们可以使用正数和负数进行字符串索引。让我们逐一讨论。
使用正数的字符串索引
正如我们在上面看到的,字符串使用正数从 0 到字符串长度-1 进行索引。我们可以使用如下的正索引来访问 0 到(字符串长度)-1 之间任何位置的字符。
myString = "PythonForbeginners"
index = 0
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 1
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 2
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 3
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 17
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
输出:
Character at index 0 in the string 'PythonForbeginners' is P.
Character at index 1 in the string 'PythonForbeginners' is y.
Character at index 2 in the string 'PythonForbeginners' is t.
Character at index 3 in the string 'PythonForbeginners' is h.
Character at index 17 in the string 'PythonForbeginners' is s.
请记住,大于或等于字符串长度的索引将导致如下 IndexError 异常。
myString = "PythonForbeginners"
index = 20
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
character = myString[index]
IndexError: string index out of range
您可以通过在访问字符串中的任何字符之前检查 index 的值来避免 IndexError 异常。或者,您可以使用 python try except 块来处理出现的异常。
在这里,我会建议你使用 try except 块。如果我们使用小于字符串长度的索引进行访问,那么每次访问一个字符时检查索引可能是多余的,而且代价很高。当使用 try except 块时,程序不会在我们每次访问字符串中的一个字符时检查 index 的值。如果发生 IndexError,它将由 except 块中的代码处理。
使用负数进行索引
我们也可以使用负索引来访问字符串中的字符。在 python 中,字符串的最后一个字符被赋予索引-1。倒数第二个字符的索引为-2。类似地,字符串的第一个字符被赋予一个索引-(字符串的长度)。
我们可以通过下面的例子来理解这一点。
假设我们有一个字符串“PythonForBeginners”
这里,字母“s”的索引是-1。字母“r”的索引是-2。字母“n”的索引是-3,字母“n”的索引是-4,依此类推。第一个字母“P”的索引是-18。
您可以使用下面的程序来验证这一点。
myString = "PythonForbeginners"
index = -1
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -2
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -3
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -4
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -18
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
输出:
Character at index -1 in the string 'PythonForbeginners' is s.
Character at index -2 in the string 'PythonForbeginners' is r.
Character at index -3 in the string 'PythonForbeginners' is e.
Character at index -4 in the string 'PythonForbeginners' is n.
Character at index -18 in the string 'PythonForbeginners' is P.
使用负数作为索引时,请确保传递的索引不小于-(字符串长度)。否则,您的程序将会遇到如下的 IndexError。
myString = "PythonForbeginners"
index = -20
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
character = myString[index]
IndexError: string index out of range
结论
在本文中,我们研究了 python 中的字符串索引。我们已经看到了如何使用负数和正数来访问字符串中的字符。要学习更多关于 python 中字符串的知识,你可以阅读这篇关于字符串连接的文章。
Python 中的字符串操作
原文:https://www.pythonforbeginners.com/basics/string-manipulation-in-python
Python 字符串是处理文本数据最有效的工具之一。在本文中,我们将讨论 python 字符串和 Python 中字符串操作的基础知识。
Python 中的字符串是什么?
一个 python 字符串是一个按顺序排列的字符列表。字符是你可以在键盘上一键输入的任何东西,
像一个字母、一个数字或一个反斜杠。
字符串可以有空格:
"hello world".
空字符串是包含 0 个字符的字符串。
Python 字符串是不可变的
Python 将所有由引号
(" "或' ')分隔的内容都识别为字符串。
Python 中的字符串操作
为了操作字符串,我们可以使用 Pythons 的一些内置方法。
创建字符串
要创建具有给定字符的字符串,您可以在将字符用双引号或单引号括起来后将其赋给变量,如下所示。
word = "Hello World"
>>> print word
Hello World
访问字符串中的字符
要访问字符串中的字符,我们可以使用 python 索引操作符[ ]即方括号来访问字符串中的字符,如下所示。
word = "Hello World"
letter=word[0]
>>> print letter
H
查找字符串的长度
要找到一个字符串的长度,我们可以使用 len()函数。len()函数将一个字符串作为输入参数,并返回字符串的长度,如下所示。
word = "Hello World"
>>> len(word)
11
在字符串中查找字符
要查找字符串中某个字符的索引,我们可以使用 find()方法。在字符串上调用 find()方法时,该方法将该字符作为其输入参数,并返回该字符第一次出现的索引,如下所示。
>>> word = "Hello World"
>>> print word.find("H") # find the word H in the string
0
您还可以在 python 中执行字符串操作,以查找字符串中某个字符的出现频率。为此,我们可以使用 count()方法。在字符串上调用 count()方法时,该方法将一个字符作为其输入参数,并返回该字符的频率,如下所示。
>>> word = "Hello World"
>>> print word.count('l') # count how many times l is in the string
3
还可以使用 index()方法在字符串中查找字符或子字符串的索引。在字符串上调用 index()方法时,该方法将一个字符或子字符串作为其输入参数,并返回该字符或子字符串第一次出现的索引,如下所示。
>>> word = "Hello World"
>>> print word.index("World") # find the letters World in the string
6
计算字符串中的空格数
要计算字符串中的空格数,可以将空格字符传递给 count()方法,如下所示。
s = "Count, the number of spaces"
>>> print s.count(' ')
8
字符串切片
要在 Python 中执行字符串操作,可以使用语法 string _ name[start _ index:end _ index]来获取字符串的子串。这里,切片操作为我们提供了一个子字符串,其中包含从字符串 string_name 的 start_index 到 end_index-1 的字符。
请记住,python 和许多其他语言一样,是从 0 开始计数的!!
word = "Hello World"
print word[0] #get one char of the word
print word[0:1] #get one char of the word (same as above)
print word[0:3] #get the first three char
print word[:3] #get the first three char
print word[-3:] #get the last three char
print word[3:] #get all but the three first char
print word[:-3] #get all but the three last character
word = "Hello World"
word[start:end] # items start through end-1
word[start:] # items start through the rest of the list
word[:end] # items from the beginning through end-1
word[:] # a copy of the whole list
Python 中的拆分字符串
您可以使用 split()方法来分割字符串,以便在 Python 中执行字符串操作。在字符串上调用 split()方法时,该方法将一个字符作为其输入参数。执行后,它在指定字符处拆分字符串,并返回子字符串列表,如下所示。
word = "Hello World"
>>> word.split(' ') # Split on whitespace
['Hello', 'World']
在上面的例子中,我们在空格字符处分割了字符串。
检查字符串是以字符开头还是以字符结尾
要检查字符串是以特定字符开头还是结尾,可以分别使用 starts with()或 ends with()方法。
对字符串调用 startswith()方法时,该方法将一个字符作为输入参数。如果字符串以给定字符开头,则返回 True。否则,它返回 False。
在字符串上调用 endswith()方法时,它接受一个字符作为输入参数。如果字符串以给定字符结尾,则返回 True。否则,它返回 False。您可以在下面的示例中观察到这一点。
word = "hello world"
>>> word.startswith("H")
True
>>> word.endswith("d")
True
>>> word.endswith("w")
False
多次重复字符串
您可以使用乘法运算符多次重复一个字符串。当我们将任何给定的字符串或字符乘以一个正数 N 时,它会重复 N 次。您可以在下面的示例中观察到这一点。
print "."* 10 # prints ten dots
>>> print "." * 10
..........
在 Python 中替换字符串中的子串
还可以使用 replace()方法将一个子字符串替换为另一个子字符串。当在字符串上调用 replace()方法时,将被替换的子字符串作为第一个输入参数,将替换字符串作为第二个输入参数。执行后,它用替换字符串替换指定的子字符串,并返回修改后的字符串。您可以使用 replace()方法在 Python 中执行字符串操作,如下所示。
word = "Hello World"
>>> word.replace("Hello", "Goodbye")
'Goodbye World'
更改大小写字符串
可以使用 upper()、lower()和 title()方法将 string 转换成大写、小写和 titlecase。
upper()方法在字符串上调用时,会将字符串变为大写并返回修改后的字符串。
lower()方法在字符串上调用时,会将字符串变为小写,并返回修改后的字符串。
title()方法在字符串上调用时,会将字符串更改为 titlsecase 并返回修改后的字符串。
还可以使用 capital()和 swapcase()方法将字符串大写或交换字符串中字符的大小写。
在字符串上调用 capitalize()方法时,会将字符串的第一个字符大写,并返回修改后的字符串。
在字符串上调用 swapcase()方法时,会将小写字符转换为大写字符,反之亦然。执行后,它返回修改后的字符串。
您可以在下面的例子中观察这些用例。
string = "Hello World"
>>> print string.upper()
HELLO WORLD
>>> print string.lower()
hello world
>>> print string.title()
Hello World
>>> print string.capitalize()
Hello world
>>> print string.swapcase()
hELLO wORLD
在 Python 中反转一个字符串
要反转字符串,可以使用 reversed()函数和 join()方法。
reversed()函数将一个字符串作为其输入参数,并以相反的顺序返回一个包含输入字符串字符的列表。
join()方法在分隔符字符串上调用时,将字符列表作为其输入参数,并使用分隔符连接列表中的字符。执行后,它返回结果字符串。
要使用 reversed()函数和 join()方法反转一个字符串,我们将首先使用 reversed()函数创建一个逆序字符列表。然后,我们将使用一个空字符串作为分隔符,并在空字符串上调用 join()方法,将字符列表作为输入参数。在执行 join()方法之后,我们将得到一个新的反向字符串,如下所示。
string = "Hello World"
>>> print ''.join(reversed(string))
dlroW olleH
在 Python 中剥离字符串
Python 字符串具有 strip()、lstrip()、rstrip()方法,用于移除字符串两端的任何字符。
strip()方法在字符串上调用时,将一个字符作为其输入参数,并从字符串的开头(左)和结尾(右)删除该字符。如果没有指定要删除的字符,则空白字符将被删除。
在字符串上调用 lstrip()方法时,将一个字符作为其输入参数,并从字符串的开头(左侧)删除该字符。
在字符串上调用 rstrip()方法时,该方法将一个字符作为其输入参数,并从字符串的末尾(右侧)删除该字符。
word = "Hello World"
通过将“\n”作为输入参数传递给 rstrip()方法,可以从字符串末尾去掉换行符。
>>> print word.strip('\n')
Hello World
strip() #removes from both ends
lstrip() #removes leading characters (Left-strip)
rstrip() #removes trailing characters (Right-strip)
>>> word = " xyz "
>>> print word
xyz
>>> print word.strip()
xyz
>>> print word.lstrip()
xyz
>>> print word.rstrip()
xyz
在 Python 中连接字符串
要在 Python 中连接字符串,请使用“+”运算符,如下所示。
"Hello " + "World" # = "Hello World"
"Hello " + "World" + "!"# = "Hello World!"
如上所述,join()方法在分隔符字符串上调用时,将字符列表作为其输入参数,并使用分隔符连接列表中的字符。执行后,它返回结果字符串。
>>> print ":".join(word) # #add a : between every char
H:e:l:l:o: :W:o:r:l:d
>>> print " ".join(word) # add a whitespace between every char
H e l l o W o r l d
测试
Python 中的字符串可以测试真值。
返回类型将是布尔值(真或假)
word = "Hello World"
word.isalnum() #check if all char are alphanumeric
word.isalpha() #check if all char in the string are alphabetic
word.isdigit() #test if string contains digits
word.istitle() #test if string contains title words
word.isupper() #test if string contains upper case
word.islower() #test if string contains lower case
word.isspace() #test if string contains spaces
word.endswith('d') #test if string endswith a d
word.startswith('H') #test if string startswith H
结论
在本文中,我们讨论了在 Python 中执行字符串操作的不同方法。要了解更多关于 python 编程的知识,你可以阅读这篇关于 Python 中的列表理解的文章。你可能也会喜欢这篇关于如何用 python 构建聊天机器人的文章。
Python 中的字符串切片
原文:https://www.pythonforbeginners.com/strings/string-slicing-in-python
字符串是 Python 中最常用的数据结构之一。我们使用 Python 中的字符串处理所有文本数据。在本文中,我们将研究使用切片从给定的字符串中提取子字符串的方法。我们还将看一些字符串切片的例子,以便更好地理解它。
什么是字符串切片?
字符串切片是取出字符串的一部分的过程。提取部分中的字符可以是连续的,或者它们可以以规则的间隔出现在原始字符串中。
您可以使用下面的类比来理解字符串切片。
假设你正在把一条面包切成片。所有的面包片,不管有多厚,都构成了一片面包。类似地,我们可以从字符串创建切片。这种类比的唯一区别是,在切片面包的情况下,原始面包在切片形成后被破坏。相反,在对字符串进行切片时,即使创建了新的切片,原始字符串仍保持原样。
让我们举一个例子。假设我们有一个字符串“ Pythonforbeginners ”。
字符串的不同部分如下:
- " Python ":这里,我们取了字符串的前六个字符。您可以从任何索引开始的原始字符串中提取任意数量的连续字符,这些字符将构成字符串的一部分。
- " nigeb ":这里,我们取了一些逆序的字符。您可以从原始字符串中以逆序从任何索引开始提取任意数量的连续字符,这些字符将构成字符串的一部分。
- " Ptof ":这里,我们取了一些间隔 1 个位置出现的字符。您可以从任何索引开始,以固定的间隔从原始字符串中提取任意数量的字符,这些字符将构成字符串的一部分。
- " sngr ":这里,我们取了一些以相反顺序出现在两个位置之间的字符。您可以从任何索引开始,以相反的顺序,以固定的间隔从原始字符串中提取任意数量的字符,这些字符将构成字符串的一部分。
在 python 中,有两种方法可以创建字符串片段。我们可以使用索引和内置的 slice()方法从字符串创建切片。让我们逐一讨论这两种方法。
使用字符串索引进行切片
我们可以使用字符的索引从字符串中创建一个片段。使用索引进行字符串切片的语法是 string_name [ start_index:end_index:step_size ] 。这里,
- start_index 是字符串中开始分段的字符的索引。
- end_index 是字符串中字符的索引,字符串的切片在该处终止。这里,end_index 是排他的,end_index 处的字符将不包括在分片字符串中。
- step_size 用于确定原始字符串中将要包含在分片字符串中的索引。
- step_size 为 1 意味着将从原始字符串的 start_index 开始到 end_index-1 结束的连续字符创建切片。
- step_size 为 2 意味着我们将使用备用字符创建原始字符串的一部分,从原始字符串的 start_index 开始,到 end_index-1 结束。
- step_size 为 3 意味着我们将在原始字符串的每个字符之间留出 2 个位置之后选择字符,这些字符必须包括在从原始字符串的 start_index 开始到 end_index-1 结束的分片字符串中。
- 如果 start_index 大于 end_index,并且 step_size 为负值,则以相反的顺序进行切片。
我们可以通过下面的例子来理解上述语法的工作原理。
myString = "Pythonforbeginners"
mySlice = myString[0:6:1]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 5, 1, mySlice))
mySlice = myString[13:8:-1]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 13, 9, -1, mySlice))
mySlice = myString[0:8:2]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 8, 2, mySlice))
mySlice = myString[18:7:-3]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 18, 7, -3, mySlice))
输出:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 and step size 1 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at index 9 and step size -1 is 'nigeb'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 8 and step size 2 is 'Ptof'
Slice of string 'Pythonforbeginners' starting at index 18, ending at index 7 and step size -3 is 'sngr'
字符串切片的另一种语法是我们只指定 start_index 和 end_index,如 string_name [ start_index:end_index] 中所示。这里,步长取为 1,字符从 start_index 到 end_index-1 连续选择,如下所示。
myString = "Pythonforbeginners"
mySlice = myString[0:6]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))
输出:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'Python'
我们也可以选择不指定 start_index 和 end_index。在这种情况下,start_index 的默认值取为 0,end_index 的默认值取为字符串的长度。您可以在下面的示例中观察到这些变化。
myString = "Pythonforbeginners"
mySlice = myString[:6]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))
mySlice = myString[13:]
print("Slice of string '{}' starting at index {}, ending at last index is '{}'".format(myString, 13, mySlice))
输出:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at last index is 'nners'
使用内置函数进行切片
我们可以使用 slice()方法,而不是直接使用字符的索引。slice()方法将 start_index、end_index 和 step_size 作为输入,并创建一个 slice 对象。然后将 slice 对象作为 index 传递给原始字符串,然后创建原始字符串的切片,如下所示。
myString = "Pythonforbeginners"
slice_obj = slice(0, 6, 1)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 5, 1,
mySlice))
slice_obj = slice(13, 8, -1)
mySlice = myString[slice_obj]
print(
"Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 13, 9, -1,
mySlice))
slice_obj = slice(0, 8, 2)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 0, 8, 2,
mySlice))
slice_obj = slice(18, 7, -3)
mySlice = myString[slice_obj]
print(
"Slice of string '{}' starting at index {}, ending at index {} and step size {} is '{}'".format(myString, 18, 7, -3,
mySlice))
输出:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 and step size 1 is 'Python'
Slice of string 'Pythonforbeginners' starting at index 13, ending at index 9 and step size -1 is 'nigeb'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 8 and step size 2 is 'Ptof'
Slice of string 'Pythonforbeginners' starting at index 18, ending at index 7 and step size -3 is 'sngr'
您可以看到,slice 对象的工作方式几乎与我们使用字符索引从字符串创建切片的方式相同。使用下面的例子可以更清楚地理解这一点。
myString = "Pythonforbeginners"
# specify only start and end index
slice_obj = slice(5, 16)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 5, mySlice))
# specify only end index
slice_obj = slice(12)
mySlice = myString[slice_obj]
print("Slice of string '{}' starting at index {}, ending at index {} is '{}'".format(myString, 0, 12, mySlice))
输出:
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 5 is 'nforbeginne'
Slice of string 'Pythonforbeginners' starting at index 0, ending at index 12 is 'Pythonforbeg'
结论
在本文中,我们讨论了 python 中的字符串切片。我们还研究了从给定字符串创建切片的不同方法。要学习更多关于 python 中字符串的知识,你可以阅读这篇关于字符串连接的文章。
Python 中的字符串拼接
原文:https://www.pythonforbeginners.com/python-strings/string-splicing-in-python
Python 字符串是用单引号、双引号或三引号括起来的字符序列。python 中的字符串是不可变的。我们可以使用 python 中的字符串拼接来访问字符串中的每个字符。拼接也被称为索引。
Python 中的字符串拼接是什么?
字符串拼接或索引是一种方法,通过这种方法,我们可以从 python 字符串中访问任何字符或字符组。在 python 中,可以在方括号[ ]的帮助下访问字符串的字符或子字符串,就像我们在 python 中访问列表中的元素一样。我们可以使用正索引和负索引来访问字符串中的字符。
在 python 中使用正索引进行字符串拼接时,字符串的第一个字符的索引为 0,后续字符的索引增加 1,直到结束。
例如,我们可以使用下面的程序打印一个字符串的第一个字符、第三个字符和第十一个字符。注意在 python 中索引是基于 0 的。即第一个字符被赋予索引 0 而不是 1。
myString="PythonForBeginners"
x=myString[0]
print(x)
x=myString[2]
print(x)
x=myString[10]
print(x)
输出
P
t
e
在 python 中使用负索引进行字符串拼接时,python 字符串的最后一个字符的索引为-1,向后移动时,每个字符的索引都比前一个字符小 1。
在下面的例子中,我们使用负索引来打印 python 字符串的字符。
myString="PythonForBeginners"
x=myString[-1]
print(x)
x=myString[-5]
print(x)
x=myString[-10]
print(x)
输出
s
n
r
如何从 python 字符串中捕获子字符串?
子字符串是 python 字符串的连续部分。它可以从任何索引开始,在任何索引结束。
使用正索引,我们可以使用方括号 [ ]操作符捕获一个子字符串。我们可以指定要包含在子字符串中的字符串的起始字符的索引和最后字符的索引。取出子字符串的语法是string_name[start_index:last_index]。位于start_index的字符包含在子字符串中,但不包含位于last_index的字符。仅包含索引last_index-1之前的字符。因此start_index是包含性的,而last_index是排他性的。
在下面给出的例子中,我们可以看到,start_index处的字符已经包含在输出中,而last_index处的字符没有包含在输出中。
myString="PythonForBeginners"
x=myString[0:5]
print(x)
x=myString[6:9]
print(x)
x=myString[0:6]
print(x)
输出
Pytho
For
Python
为了捕获从开始到给定索引的子字符串,我们可以将start_index值留空。
myString="PythonForBeginners"
x=myString[:6]
print(x)
x=myString[:9]
print(x)
x=myString[:18]
print(x)
输出
Python
PythonFor
PythonForBeginners
要捕获从给定索引开始到最后一个索引结束的字符串,我们可以简单地将last_index值留空。
myString="PythonForBeginners"
x=myString[0:]
print(x)
x=myString[6:]
print(x)
x=myString[9:]
print(x)
输出
PythonForBeginners
ForBeginners
Beginners
我们也可以使用负索引从 python 字符串中捕获子字符串,方法同上。
myString="PythonForBeginners"
x=myString[-10:-1]
print(x)
x=myString[:-1]
print(x)
x=myString[-5:-1]
print(x)
输出
rBeginner
PythonForBeginner
nner
python 中的子字符串也是字符串,我们可以执行类似于字符串连接、 python 字符串分割等操作
例如,我们可以执行字符串连接,如下例所示。
myString="PythonForBeginners"
x1=myString[:6]
x2=myString[6:9]
x3=myString[9:]
x=x1+x2+x3
print(x)
输出:
PythonForBeginners
如何从 python 字符串中捕获一个子序列?
python 字符串的子序列是从字符串中取出的字符序列,不会打乱字符在字符串中的顺序。子序列中的字符可能是输入 python 字符串的连续字符,也可能不是。
为了捕获子序列,我们使用方括号 [ ] 操作符。从字符串中捕获子序列的语法是string_name[start_index,end_index,difference]。difference表示要加到start_index上的数字,以获得要包含在子序列中的下一个字符的索引,在子序列中包含一个字符后,跳过difference-1字符。
myString="PythonForBeginners"
x=myString[0:10:2]
print(x)
x=myString[0:10:3]
print(x)
输出
PtoFr
PhFB
结论
在本文中,我们研究了 python 中的字符串拼接。我们还看到了如何使用字符串拼接从 python 字符串中捕获子字符串和子序列。请继续关注更多内容丰富的文章。
Python 中的字符串到整数
原文:https://www.pythonforbeginners.com/strings/string-to-integer-in-python
在用 Python 编程的过程中,我们经常需要在 Python 中将一个字符串转换成一个整数。这是因为 Python 中的标准输入总是被读取为独立于输入类型的字符串。为了在我们的程序中使用整数数据,当它作为空格分隔的整数被传递时,我们需要在使用 Python string split 操作分割它们之后将字符串输入转换成整数。在这篇文章中,我们将看看如何将一个字符串正确无误地转换成整数,并用 Python 实现这些程序。
Python 中如何把字符串转换成整数?
在 Python 中我们可以使用 int()函数将一个字符串转换成整数。必须转换为整数的字符串作为输入参数传递给 int()函数,如果作为输入传递的字符串格式正确,并且在字符串转换为整数的过程中没有发生错误,则该函数返回相应的整数值。我们可以使用 int()函数将字符串转换为整数,如下所示。
print("Input String is:")
myInput= "1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
1117
Output Integer is:
1117
当输入字符串的格式不正确时,int()函数会引发 ValueError。这可以从下面的例子中看出。
print("Input String is:")
myInput= "aditya1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
aditya1117
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-3-c8793975130e>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: 'aditya1117'
将字符串转换为整数时,哪些输入值会出现错误?
在几种情况下,int()函数在将字符串转换为整数时会引发 ValueError。下文讨论了一些案例。
当我们传递一个包含字母而不是数字的字符串时,将会发生 ValueError,并且输入字符串不会被转换成整数。这可以从下面的例子中看出。
print("Input String is:")
myInput= "aditya1117"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
aditya1117
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-10-c8793975130e>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int()
当传递的字符串包含任何空格字符和数字文字时,将发生 ValueError,并且输入字符串不会转换为整数。这可以从下面的例子中看出。
print("Input String is:")
myInput= "11 17"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
11 17
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-4-46d411efb04b>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '11 17'
当传递的字符串包含任何标点符号(如句点字符。)或逗号(,)以及数字文字,将出现 ValueError,并且输入字符串不会转换为整数。这可以从下面的例子中看出。
print("Input String is:")
myInput= "11.17"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
11.17
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-5-97993fa7ba5b>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '11.17'
在将字符串转换为整数时如何避免 ValueError?
在 Python 中将字符串转换为整数时,我们可以先发制人地检查传递的字符串是否只包含数字,这样我们就可以避免错误的发生,或者我们可以使用 Python try except 来处理由 int()函数引发的 ValueError。下面讨论了这两种方法。
我们可以使用 isdigit()方法来检查一个字符串是否只包含数字字符。对字符串调用 isdigit()方法时,如果字符串仅由数字组成,则返回 true。否则返回 false。这可以如下实现。
print("Input String is:")
myInput= "1117"
print(myInput)
if myInput.isdigit():
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
else:
print("Input cannot be converted into integer.")
输出:
Input String is:
1117
Output Integer is:
1117
如果输入字符串包含数字以外的字符,输出将如下所示。
print("Input String is:")
myInput= "aditya1117"
print(myInput)
if myInput.isdigit():
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
else:
print("Input cannot be converted into integer.")
输出:
Input String is:
aditya1117
Input cannot be converted into integer.
为了在 ValueError 发生后对其进行处理,我们可以使用异常处理,使用 Python try except 来处理 ValueError 并向用户显示正确的消息,如下所示。
print("Input String is:")
myInput= "1117"
print(myInput)
try:
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
except ValueError:
print("Input cannot be converted into integer.")
输出:
Input String is:
1117
Output Integer is:
1117
如果输入字符串包含数字以外的字符,输出将如下所示。
print("Input String is:")
myInput= "aditya1117"
print(myInput)
try:
myInt=int(myInput)
print("Output Integer is:")
print(myInt)
except ValueError:
print("Input cannot be converted into integer.")
输出:
Input String is:
aditya1117
Input cannot be converted into integer.
结论
在本文中,我们看到了如何在 Python 中将字符串转换为整数,以及在转换过程中会出现什么问题。我们还看到了如何避免和处理在字符串到整数的转换过程中由 int()函数引发的 ValueError。请继续关注更多内容丰富的文章。
字符串内置方法
原文:https://www.pythonforbeginners.com/basics/strings-built-in-methods
字符串内置方法
在这篇文章中,我想展示如何使用 python 字符串的内置方法。让我们首先创建一个值为“Hello World”的字符串
string = "Hello World"
为了操作字符串,我们可以使用 Pythons 的一些内置方法
string.upper() # get all-letters in uppercase
string.lower() # get all-letters in lowercase
string.capitalize() # capitalize the first letter
string.title() # capitalize the first letter of words
string.swapcase() # converts uppercase and lowercase
string.strip() # remove all white spaces
string.lstrip() # removes white space from left
string.rstrip() # removes white space from right
string.split() # splitting words
string.split(',') # split words by comma
string.count('l') # count how many times l is in the string
string.find('Wo') # find the word Wo in the string
string.index("Wo") # find the letters Wo in the string
":".join(string) # add a : between every char
" ".join(string) # add a white space between every char
len(string) # find the length of the string
如何使用字符串计数方法
原文:https://www.pythonforbeginners.com/code-snippets-source-code/strings-count-method
计算字符串的出现次数
这个小脚本将使用 Pythons count 方法来计算一个字符串出现的次数。
s = "Count, the number of spaces."
print s.count(" ")
x = "I like to program in Python"
print x.count("i")
Python 中的字符串格式
原文:https://www.pythonforbeginners.com/basics/strings-formatting
字符串格式化是一种将变量或另一个字符串插入预定义字符串的方法。每当我们需要向字符串中插入用户输入时,我们都可以使用字符串格式。在本文中,我们将在 python 中实现字符串格式化,并使用不同的示例来理解它。
python 中的字符串格式化是什么?
字符串格式化是将变量值插入到字符串中的过程,以使程序员能够在不需要执行字符串连接的情况下向字符串添加新值。
如果用户输入他的年龄,程序需要打印句子“用户 x 岁”其中 x 是作为输入给出的用户年龄。在这种情况下,为了打印输出句子,我们使用如下的字符串连接。
myInput = input("Input your age:")
try:
age = int(myInput)
print("User is "+str(age)+" years old.")
except:
print("Input is not in correct format")
输出:
Input your age:12
User is 12 years old.
通过使用字符串格式化,可以实现上述程序,从而在不使用字符串连接的情况下给出相同的结果。
如何执行字符串格式化?
为了在 python 中执行字符串格式化,我们使用 format()方法。
首先,我们用花括号{}将一些占位符放在字符串中要放置输入变量的位置。当在包含占位符的字符串上调用 format()方法时,它接受与字符串中占位符数量相等的输入参数,并以连续的方式将输入放在占位符的位置。
myInput = input("Input your age:")
try:
age = int(myInput)
print("User is {} years old.".format(age))
except:
print("Input is not in correct format")
输出:
Input your age:12
User is 12 years old.
我们也可以给 format()方法多个参数。当多个参数作为输入传递给方法时,它会用相应的参数替换占位符。
例如,假设用户将他/她的姓名和年龄作为输入输入到程序中,我们必须打印一个句子“用户 y 是 x 岁。”其中 y 是用户的姓名,x 是用户的年龄。我们将这样做。
myName=input("Input your name:")
myInput = input("Input your age:")
try:
age = int(myInput)
print("User {} is {} years old.".format(myName, age))
except:
print("Input is not in correct format")
输出:
Input your name:Aditya
Input your age:22
User Aditya is 22 years old.
我们也可以给占位符分配索引。通过给占位符分配索引,我们可以按一定的顺序提供输入参数,相应索引处的大括号将被输入参数替换。
在这种方法中,输入不会连续映射到占位符。它们根据索引进行映射。这可以从下面的程序中理解。
myName=input("Input your name:")
myInput = input("Input your age:")
try:
age = int(myInput)
print("User {1} is {0} years old.".format(age,myName))
except:
print("Input age is not in correct format")
输出:
Input your name:Aditya
Input your age:22
User Aditya is 22 years old.
format()方法也接受关键字参数。为了将输入作为关键字参数传递给 format 方法,我们首先命名占位符。随后,我们通过使用占位符名称作为关键字,将输入参数传递给方法。这可以从下面的例子中看出。
myName=input("Input your name:")
myInput = input("Input your age:")
try:
myAge = int(myInput)
print("User {name} is {age} years old.".format(age=myAge,name=myName))
except:
print("Input is not in correct format")
输出:
Input your name:Aditya
Input your age:22
User Aditya is 22 years old.
使用占位符和 format()方法,我们还可以格式化程序中使用的输入浮点数,如下所示。
myInput = input("Input a number:")
try:
myNum = float(myInput)
print("Input number is: {:.2f}".format(myNum))
except:
print("Input is not in correct format")
输出:
Input a number:12.2345
Input number is: 12.23
结论
在本文中,我们研究了使用 format()方法实现不同类型的字符串格式..我们必须使用 python try except 编写本文中使用的异常处理程序,以使程序更加健壮,并以系统的方式处理错误,以便在将输入从字符串转换为整数或浮点时不会出现错误。请继续关注更多内容丰富的文章。请继续关注更多内容丰富的文章。
Yoast SEO
Python 字符串引号
概观
字符串可以用单引号或双引号括起来。
单引号字符串可以包含双引号,双引号字符串可以
包含单引号。字符串也可以以多种方式跨越多行。
换行符可以用反斜杠转义,但是每行的
结尾必须有一个反斜杠来转义换行符。
字符串可以用一对匹配的三重引号括起来:" "(双引号)
或" '(单引号)
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
will show this output:
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
最后,我们有原始字符串。
原始字符串禁止转义,所以
序列不会被转换成
换行符,但是行尾的反斜杠和源中的
换行符都作为数据包含在字符串中。
“r”可以是小写或大写,并且必须放在第一个引号
之前。
hello = r"This is a rather long string containing
several lines of text."
print hello
将显示以下输出:
这是一个相当长的字符串,包含
几行文字。
使用单引号还是双引号并不重要,只要确保如果用双引号开始一个值,就必须用双引号结束它。
我通常对正则表达式使用原始字符串,对文档字符串使用三重引号
请看一下字符串备忘单了解更多关于 Python 中字符串
的事情。
Python 中的剥离字符
原文:https://www.pythonforbeginners.com/basics/strings-strip-lstrip-and-rstrip
剥离方法
Python 字符串具有 strip()、lstrip()、rstrip()方法,用于移除字符串两端的任何字符。如果没有指定要删除的字符,则空白将被删除
strip()#从两端移除
lstrip()#删除前导字符(左条)
rst rip()#删除尾部字符(右移)
例子
spacious = " xyz "
print spacious.strip()
spacious = " xyz "
print spacious.lstrip()
spacious = "xyz "
print spacious.rstrip()
更多阅读
Python 中的字符串是什么?
什么是字符串?
字符串是按顺序排列的字符列表。
字符是你可以在键盘上一次击键输入的任何东西,比如一个字母、一个数字或一个反斜杠。
字符串可以有空格:“hello world”。
空字符串是包含 0 个字符的字符串。
Python 字符串是不可变的
Python 将所有由引号(“”或“)分隔的内容都识别为字符串。
访问字符串
**Use [ ] to access characters in a string:**
word = "computer"
letter = word[0]
**Use [ # :#] to get set of letters**
word= word[0:3]
**To pick from beginning to a set point:**
word = [:4]
**To pick from set point to end:**
word = [3:]
**To pick starting from the end:**
word = [-1]
引用
**Strings can be enclosed in single quotes**
print 'Hello World in single quotes'
**Strings can also be enclosed in double quotes**
print "Hello World in double quotes"
**Strings can also be enclosed in triple quotes**
print """ This is a multiline string
Such strings are also possible in Groovy.
These strings can contain ' as well as " quotes """
**Strings can be continued on the next line**
print "This string is continued on the
next line (in the source) but a newline is not added"
Raw Strings
原始字符串的存在是为了让您可以更方便地表达将被转义序列处理修改的字符串。
这在写出正则表达式或其他字符串形式的代码时尤其有用。
连接字符串
在 Python 中,有几种不同的方法来将字符串连接起来。串联将两个(或多个)字符串组合成一个新的字符串对象。
你可以使用+运算符,就像这样:
print "You can concatenate two " + "strings with the '+' operator."
str1 = "Hello"
str2 = "World"
str1 + str2 # concatenation: a new string
字符串可以用空格连接
word = 'left' "right" 'left'
任何字符串表达式都可以用+ 连接
word = wordA + "
" + wordB
反向字符串
string = "Hello World"
print ' '.join(reversed(string))
>>Output:
d l r o W o l l e H
更改大小写字符串
string = "Hello World"
print string.lower()
print string.upper()
print string.title()
替换字符串
string = "Hello World"
string.replace("你好"、"再见")
重复字符串
print "."* 10 # prints ten dots( print string * n ; prints the string n times)
拆分字符串
Python 有一个非常简洁的函数,可以将字符串分解成更小的字符串。
split 函数使用定义的分隔符
将单个字符串拆分成一个字符串数组。如果没有定义分隔符,则使用空白。
x = 'blue,red,green'
x.split(",")
['blue', 'red', 'green']
word = "This is some random text"
words2 = word.split(" ")
print words
['This', 'is', 'some', 'random', 'text']
开始/结束
Checking if a string starts or ends with a substring:
s = "hello world"
s.startswith("hello")
True
s.endswith("rld")
True
条状字符串
Python 字符串具有 strip()、lstrip()、rstrip()方法,用于移除字符串两端的任何字符。
如果没有指定要删除的字符,则空白将被删除。
string = "Hello World"
#Strip off newline characters from end of the string
print string.strip('
')
strip() #removes from both ends
lstrip() #removes leading characters (Left-strip)
rstrip() #removes trailing characters (Right-strip)
spacious = " xyz "
print spacious.strip()
spacious = " xyz "
print spacious.lstrip()
spacious = "xyz "
print spacious.rstrip()
分割字符串
字符串是有索引的,所以我们可以用对应的索引来引用字符串的每一个位置。请记住,python 和许多其他语言一样,是从 0 开始计数的!!
print string[1] #get one char of the word
print string[1:2] #get one char of the word (same as above)
print string[1:3] #get the first three char
print string[:3] #get the first three char
print string[-3:] #get the last three char
print string[3:] #get all but the three first char
print string[:-3] #get all but the three last character
x = "my string"
x[start:end] # items start through end-1
x[start:] # items start through the rest of the list
x[:end] # items from the beginning through end-1
x[:] # a copy of the whole list
格式化字符串
下面是 python 中字符串格式化的几个例子。
带%的字符串格式
百分比“%”字符标记说明符的开始。
%s #用于字符串
%d #用于数字
%f #用于浮点
x = 'apple'
y = 'lemon'
z = "篮子里的物品是%s 和%s" % (x,y)
注意:确保对值使用元组。
使用{ }设置字符串格式
成对的空花括号{}充当我们要放在字符串中的变量的占位符。
然后,我们将这些变量按顺序作为 strings format()方法的输入传递到我们的字符串中。
有了这个方法,我们不需要先把整数转换成字符串类型,format 方法会自动完成。
fname = "Joe"
lname = "Who"
age = "24"
#Example of how to use the format() method:
print "{} {} is {} years ".format(fname, lname, age)
#Another really cool thing is that we don't have to provide the inputs in the
#same order, if we number the place-holders.
print "{0} {1} is {2} years".format(fname, lname, age)
连接字符串
这个方法接受一个字符串列表,并用每个元素之间的调用字符串将它们连接在一起。
>>> ' '.join(['the', 'cat', 'sat', 'on', 'the', 'mat'])
'the cat sat on the mat'
#Let's look at one more example of using the Join method:
#creating a new list
>>> music = ["Abba","Rolling Stones","Black Sabbath","Metallica"]
#Join a list with an empty space
>>> print ' '.join(music)
#Join a list with a new line
>>> print "
".join(music)
测试字符串
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
内置字符串方法
String 方法在调用它的字符串上工作!这些是内置的字符串方法。(使用点符号)
>>string.string_method()
string = "Hello World"
为了操作字符串,我们可以使用 Pythons 的一些内置方法
string.upper() #get all-letters in uppercase
string.lower() #get all-letters in lowercase
string.capitalize() #capitalize the first letter
string.title() #capitalze the first letter of words
string.swapcase() #converts uppercase and lowercase
string.strip() #remove all white spaces
string.lstrip() #removes whitespace from left
string.rstrip() #removes whitespace from right
string.split() #splitting words
string.split(',') #split words by comma
string.count('l') #count how many times l is in the string
string.find('Wo') #find the word Wo in the string
string.index("Wo") #find the letters Wo in the string
":".join(string) #add a : between every char
" ".join(string) #add a whitespace between every char
len(string) #find the length of the string
string.replace('World', 'Tomorrow') #replace string World with Tomorrow
来源
https://github.com/adaptives/python-examples
http://en.wikibooks.org/wiki/Python_Programming
Python 中的子流程和 Shell 命令
原文:https://www.pythonforbeginners.com/os/subprocess-for-system-administrators
子流程概述
很长一段时间以来,我一直使用 os.system()来处理 Python 中的系统
管理任务。
主要原因是,我认为这是运行 Linux 命令最简单的方式。
在官方的 python 文档中,我们可以看到应该使用子进程
来访问系统命令。
子流程模块允许我们生成流程,连接到它们的
输入/输出/错误管道,并获得它们的返回代码。
子进程旨在替换其他几个较旧的模块和函数,如:os.system、os.spawn、os.popen、popen2。*命令。
让我们开始研究子流程的不同功能。
subprocess.call()
运行“args”描述的命令。
我们可以运行命令行,将参数作为字符串列表
(示例 1)传递,或者将 shell 参数设置为 True 值(示例 2)
注意,shell 参数的默认值是 False。
让我们看两个例子,在这两个例子中,我们使用
subprocess.call()显示了磁盘使用情况的摘要
subprocess.call(['df', '-h'])
这一次我们将 shell 参数设置为 True
subprocess.call('du -hs $HOME', shell=True)
注意,官方 Python 文档对使用
shell=True 参数提出了警告。
“使用 shell=True 调用系统 shell,如果将
与不受信任的输入结合起来,可能会有安全隐患”[ 来源
现在,让我们继续,看看输入/输出。
输入和输出
使用 subprocess,您可以取消输出,这在您想要运行系统调用但对标准输出不感兴趣时非常方便。
它还为您提供了一种方法,在以标准方式管理输入/输出的同时,将 shell 命令干净地集成到您的脚本
中。
返回代码
您可以使用 subprocess.call 返回代码来确定命令是否成功。
每个进程都会返回一个退出代码,你可以根据这个代码用你的脚本
做一些事情。
如果返回代码不是零,则意味着发生了错误。
如果想用 Python 做系统管理,推荐阅读
Python for Unix 和 Linux 系统管理
stdin, stdout and stderr
我在 subprocess 中遇到的最棘手的部分之一是如何使用管道
和管道命令。
管道表示应该创建一个到子管道的新管道。
默认设置是“无”,这意味着不会发生重定向。
标准错误(或 stderr)可以是 stdout,这表明来自子进程的 stderr
数据应该被捕获到与 STDOUT 的
相同的文件句柄中。
子流程。波本()
子流程模块中的底层流程创建和管理由 Popen 类
处理。subprocess.popen 正在替换 os.popen。
让我们从一些真实的例子开始。
子流程。Popen 接受一个参数列表
import subprocess
p = subprocess.Popen(["echo", "hello world"], stdout=subprocess.PIPE)
print p.communicate()
>>>('hello world', None)
注意,尽管您可以使用“shell=True ”,但这不是推荐的方式。
如果您知道您将只使用特定的子流程函数,比如 Popen 和 PIPE,那么只导入它们就足够了。
from subprocess import Popen, PIPE
p1 = Popen(["dmesg"], stdout=PIPE)
print p1.communicate()
Popen.communicate()
communicate()方法返回一个元组(stdoutdata,stderrdata)。
Popen.communicate()与 process: Send data to stdin 交互。
从 stdout 和 stderr 读取数据,直到到达文件结尾。
等待进程终止。
可选的输入参数应该是一个发送到
子进程的字符串,如果没有数据发送到子进程,则为 None。
基本上,当您使用 communicate()时,这意味着您想要
执行命令
使用子进程的 Ping 程序
在下面的“更多阅读”部分,您可以找到链接来阅读更多关于子流程模块的
,以及示例。
让我们编写自己的 ping 程序,首先向用户请求输入,
,然后对该主机执行 ping 请求。
# Import the module
import subprocess
# Ask the user for input
host = raw_input("Enter a host to ping: ")
# Set up the echo command and direct the output to a pipe
p1 = subprocess.Popen(['ping', '-c 2', host], stdout=subprocess.PIPE)
# Run the command
output = p1.communicate()[0]
print output
让我们再举一个例子。这次我们使用 host 命令。
target = raw_input("Enter an IP or Host to ping:
")
host = subprocess.Popen(['host', target], stdout = subprocess.PIPE).communicate()[0]
print host
我建议您阅读下面的链接,以获得更多关于 Python 中的
子流程模块的知识。
如果您有任何问题或意见,请使用下面的评论栏。
更多阅读
如何在 Python 中 sh
http://docs.python.org/2/library/subprocess.html
曾经有用而整洁的子流程模块
http://pymotw.com/2/subprocess/
http://www . bogoto bogo . com/Python/Python _ subprocess _ module . PHP
Python 中列表中元素的总和
原文:https://www.pythonforbeginners.com/basics/sum-of-elements-in-a-list-in-python
Python 列表是最常用的数据结构之一。我们经常需要对列表执行不同的操作。在本文中,我们将讨论在 python 中查找列表中元素之和的不同方法。
使用 For 循环查找列表中元素的总和
查找列表中元素总和的第一种方法是遍历列表,并使用循环的将每个元素相加。为此,我们将首先使用 len()方法计算列表的长度。之后,我们将声明一个变量sumOfElements为 0。之后,我们将使用 range()函数创建一个从 0 到(length of the list-1)的数字序列。使用这个序列中的数字,我们可以访问给定列表的元素,并将它们添加到sumOfElements中,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
list_length=len(myList)
sumOfElements=0
for i in range(list_length):
sumOfElements=sumOfElements+myList[i]
print("Sum of all the elements in the list is:", sumOfElements)
输出:
The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45
或者,我们可以使用 for 循环直接遍历列表。这里,我们将直接访问列表中的每个元素,并将它们添加到sumOfElements中,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
sumOfElements = 0
for element in myList:
sumOfElements = sumOfElements + element
print("Sum of all the elements in the list is:", sumOfElements)
输出:
The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45
使用 While 循环查找列表中元素的总和
我们还可以使用一个 while 循环来查找列表中元素的总和。为此,我们将首先使用 len()方法计算列表的长度。之后,我们将初始化名为 count 和sumOfElements的变量。我们将把两个元素都初始化为 0。
在 while 循环中,我们将使用 count 变量访问列表中的每个元素,并将它们添加到sumOfElements。之后,我们会将计数值增加 1。我们将继续这个过程,直到计数等于列表的长度。
你可以用 python 写一个程序来求一个列表中元素的和,如下。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
list_length = len(myList)
sumOfElements = 0
count = 0
while count < list_length:
sumOfElements = sumOfElements + myList[count]
count = count + 1
print("Sum of all the elements in the list is:", sumOfElements)
输出:
The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45
使用 Sum()函数对列表中的元素求和
Python 还为我们提供了一个内置的 sum()函数来计算任何集合对象中元素的总和。sum()函数接受一个 iterable 对象,如 list、tuple 或 set,并返回该对象中元素的总和。
可以使用 sum()函数计算列表元素的总和,如下所示。
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
sumOfElements = sum(myList)
print("Sum of all the elements in the list is:", sumOfElements)
输出:
The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45
结论
在本文中,我们讨论了用 python 查找列表中元素总和的不同方法。要阅读更多关于 python 中的列表,你可以阅读这篇关于如何在 python 中比较两个列表的文章。你可能也会喜欢列表中的这篇文章。
在 Python 中禁止异常
原文:https://www.pythonforbeginners.com/basics/suppress-exceptions-in-python
在 python 中,我们通常使用 try-except 块来处理 python 中的异常。如果我们不想处理异常怎么办?如果我们只想忽略例外呢?在本文中,我们将讨论如何在 python 中抑制异常
Python 中的异常处理
当程序中出现异常时,程序的执行会突然中断。例如,如果我们试图将一个数除以 0,将会发生异常,程序将给出如下异常回溯,如下所示。
num1 = 10
num2 = 0
print("The first number is:", num1)
print("The second number is:", num2)
output = num1 / num2
print("The output is:", output)
输出:
The first number is: 10
The second number is: 0
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/webscraping.py", line 5, in <module>
output = num1 / num2
ZeroDivisionError: division by zero
当一个程序突然停止时,该程序所做的所有工作都将丢失。为了确保程序在保存工作后执行,我们通常使用如下的 python try-except 块来处理异常。
try:
num1 = 10
num2 = 0
print("The first number is:", num1)
print("The second number is:", num2)
output = num1 / num2
print("The output is:", output)
except:
print("Exception occurred.")
输出:
The first number is: 10
The second number is: 0
Exception occurred.
这里,业务逻辑写在 try 块中,处理异常的代码写在 except 块中。现在,让我们看看如何使用 try-except 块来抑制异常。
在 Python 中使用 Try-Except 抑制异常
抑制异常意味着我们不会显式地处理异常,并且它不应该导致程序终止。使用 python 中的 try-except 块和 pass 语句,我们可以抑制 python 中的异常。pass 语句用作空语句。执行时,它什么也不做。
为了抑制异常,我们可以在 except 块中使用 pass,而不是异常处理代码。这样,异常也将得到处理,如果发生异常,也不会做额外的工作。您可以使用带有 try-except 块的 pass 语句来抑制 python 中的异常,如下所示。
try:
num1 = 10
num2 = 0
print("The first number is:", num1)
print("The second number is:", num2)
output = num1 / num2
print("The output is:", output)
except:
pass
输出:
The first number is: 10
The second number is: 0
使用 Python 中的 contextlib 模块抑制异常
不使用 try-except 块和 pass 语句,我们可以使用contextlib模块来抑制 python 中的异常。在这种方法中,我们将使用 which 语句和suppress()函数创建一个上下文,将异常作为输入参数提供给suppress()方法。
每当上下文中出现异常时,python 解释器会自动抑制它。您可以在下面的示例中观察到这一点。
import contextlib
with contextlib.suppress(Exception):
num1 = 10
num2 = 0
print("The first number is:", num1)
print("The second number is:", num2)
output = num1 / num2
print("The output is:", output)
输出:
The first number is: 10
The second number is: 0
结论
在本文中,我们讨论了在 python 中抑制异常的两种方法。想了解更多关于 python 编程的知识,可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的字典理解的文章。
用 Python 截图
原文:https://www.pythonforbeginners.com/basics/take-screenshots-in-python
我们经常需要在我们的 PC 或笔记本电脑上截图,以捕捉视频或网站上的图像。在本文中,我们将讨论 python 中截图的两种方式。
使用 Python 中的 pyautogui 模块截图
我们可以使用 pyautogui 模块在 python 中截图。除了 pyautogui 模块,我们还需要 OpenCV 和 numpy 模块来捕获屏幕截图。您可以使用 PIP 安装这些模块,如下所示。
pip install pyautogui numpy opencv-python
安装模块后,您可以在程序中使用它们。pyautogui模块为我们提供了screenshot()函数,在这个函数的帮助下我们可以截图。执行screenshot() 函数时,返回 RGB 格式的 PIL(python 图像库)文件。首先,我们将使用numpy.array() 函数将 PIL 文件转换成一个 numpy 数组。
创建 numpy 数组后,我们将把图像的 RGB 格式转换成 BGR 格式,然后再存储到存储器中。为此,我们将使用opencv.cvtColor()函数来执行该操作。opencv.cvtColor() 将前一步中创建的 numpy 数组作为其第一个输入参数,并将常量cv2.COLOR_RGB2BGR作为其第二个输入参数,以表明我们正在将 RGB 格式转换为 BGR 格式。执行后,opencv.cvtColor()返回最终图像。
为了存储最终的截图,我们将使用 cv2.imwrite()函数。它将图像文件的名称作为第一个输入参数,将表示图像的数组作为第二个输入参数。执行imwrite()功能后,屏幕截图保存在永久存储器中。
下面是使用pyautogui和opencv模块在 python 中截屏的代码。
import cv2
import pyautogui
import numpy
pil_file = pyautogui.screenshot()
numpy_arr = numpy.array(pil_file)
image = cv2.cvtColor(numpy_arr, cv2.COLOR_RGB2BGR)
cv2.imwrite('screenshot.png', image)
输出:

使用 Python 中的 pyscreenshot 模块截图
在使用pyautogui模块截图时,我们必须执行各种操作来生成输出图像。为了避免麻烦,我们可以使用 Python 中的pyscreenshot模块截图。
pyscreenshot模块为我们提供了grab()函数,借助它可以截图。grab()函数在执行时以数组的形式返回屏幕截图。您可以使用pyscreenshot模块中定义的save()方法将截图保存在存储器中。当在包含使用grab() 函数捕获的图像的数组上调用save()方法时,该方法将文件名作为输入参数,并将图像保存在存储器中。
import pyscreenshot
image = pyscreenshot.grab()
image.save('Output_screenshot.png')
输出:

您还可以使用在pyscreenshot模块中定义的show()方法来查看截图。当在包含使用grab() 函数捕获的图像的数组上调用show()方法时,会在屏幕上显示图像。
结论
在本文中,我们讨论了 python 中截图的两种方式。要了解更多关于 python 编程的知识,你可以阅读这篇关于 python 中的列表理解的文章。你可能也会喜欢这篇关于 python 中的集合理解的文章。
用 Python 终止程序
原文:https://www.pythonforbeginners.com/basics/terminate-a-program-in-python
在 python 中编写程序时,可能需要在满足某个条件后多次结束程序。在本文中,我们将讨论在 python 中终止程序的不同方法。
使用 quit()函数终止程序
quit()函数是一个内置函数,可以用来终止 python 中的程序。当执行quit()函数时,它会引发SystemExit异常。这导致了程序的终止。您可以在下面的示例中观察到这一点。
number = 10
if number >= 10:
print("The number is:", number)
quit()
print("This line will not be printed")
输出:
The number is: 10
quit()功能是在现场模块中定义的,只有在安装了模块的情况下才起作用。因此,我建议您不要在实际应用程序中使用该函数。然而,在编写更小的程序时,您可以使用quit()函数。
使用 exit()函数终止程序
站点模块中也定义了exit()功能。它的工作方式类似于quit()函数,并在执行时终止程序,如下例所示。
number = 10
if number >= 10:
print("The number is:", number)
exit()
print("This line will not be printed")
输出:
The number is: 10
同样,我建议您不要在生产环境中使用这个函数,因为它依赖于模块。
使用 sys.exit()函数终止程序
sys模块包含在核心 python 安装中。您可以按如下方式导入sys模块。
import sys
要使用 sys 模块终止程序,我们将使用 sys.exit()函数。sys.exit()函数在执行时将一个字符串消息作为可选的输入参数,并在终止程序之前打印该消息,如下所示。
import sys
number = 10
if number >= 10:
print("The number is:", number)
sys.exit()
print("This line will not be printed")
输出:
The number is: 10
但是,传递除 0 以外的任何输入参数都意味着程序异常终止。
使用 SystemExit 异常
以上所有函数都会引发SystemExit异常来终止程序。因此,我们也可以显式地调用SystemExit程序来终止 python 中的程序,如下所示。
import sys
number = 10
if number >= 10:
print("The number is:", number)
raise SystemExit
print("This line will not be printed")
输出:
The number is: 10
结论
在本文中,我们看到了在 python 中终止程序的不同方法。终止程序的最好方法是使用 StackOverflow 上许多人讨论过的sys.exit()函数。所以,我建议你用这个函数来终止一个程序。要了解更多关于 python 编程的知识,你可以在列表理解上阅读这篇文章。您可能也会喜欢这篇关于 python 中字符串连接的文章。
Python 中的文本分析
原文:https://www.pythonforbeginners.com/basics/text-analysis-in-python
分析文本数据是在自然语言处理、机器学习和相关领域工作的人生活中最常见的任务之一。我们需要找到模式,搜索特定的字符串,用另一个字符替换一个字符,并执行许多这样的任务。本文讨论如何在 Python 中使用正则表达式进行文本分析。本文讨论了各种概念,如正则表达式函数、模式和字符类以及量词。
Python 中用于文本分析的正则表达式函数
Python 为我们提供了实现和使用正则表达式的 re 模块。re 模块包含各种函数,可以帮助您在 Python 中进行文本分析。让我们逐一讨论这些功能。
match()函数
re.match()函数用于检查字符串是否以某种模式开始。re.match()函数将一个模式作为其第一个输入参数,将一个输入字符串作为其第二个输入参数。执行后,如果输入字符串不是以给定的模式开头,它将返回None。
如果输入字符串以给定的模式开始,match()函数返回一个 match 对象,它包含字符串中模式的跨度。您可以在下面的示例中观察到这一点。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="ACAA"
match_obj=re.match(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("Match object is",match_obj)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: ACAA
Match object is <re.Match object; span=(0, 4), match='ACAA'>
在这里,您可以观察到 match 对象包含匹配的字符串以及它在原始字符串中的位置。
您也可以使用group()方法在匹配对象中打印图案。在 match 对象上调用group()方法时,将从字符串中返回匹配的文本,如下例所示。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="ACAA"
match_obj=re.match(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("Text in match object is",match_obj.group())
print("Span of text is:",match_obj.span())
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: ACAA
Text in match object is ACAA
Span of text is: (0, 4)
在本例中,我们还使用span() 方法打印了匹配的子字符串的位置。在 match 对象上调用 span()方法时,它返回一个元组,该元组包含原始字符串中匹配子字符串的开始和结束索引。
search()函数
search()函数用于检查模式是否存在于输入字符串中。search()函数将一个模式作为其第一个输入参数,将一个字符串作为其第二个输入参数。执行后,如果给定的模式在字符串中不存在,它返回None。
如果模式出现在字符串中,search()函数返回一个 match 对象,其中包含模式在字符串中第一次出现的位置。您可以在下面的示例中观察到这一点。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="AA"
print("The text is:",text)
print("The pattern is:",pattern)
output=re.search(pattern,text)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: AA
The output is: <re.Match object; span=(2, 4), match='AA'>
可以看到search()函数是对match()函数的升级。但是,它只检查给定模式在字符串中的第一次出现。为了在一个字符串中找到给定模式的所有出现,我们可以使用findall()函数。
findall()函数
re 模块中的findall() 函数用于查找字符串中遵循给定模式的所有子字符串。findall()函数将一个模式作为其第一个输入参数,将一个字符串作为其第二个输入参数。执行后,如果给定的模式在字符串中不存在,它将返回一个空列表。
如果输入字符串包含遵循给定模式的子字符串,findall()函数将返回一个包含所有匹配给定模式的子字符串的列表。您可以在下面的示例中观察到这一点。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="AA"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: AA
The output is: ['AA', 'AA', 'AA', 'AA', 'AA']
这里,findall()函数返回了原始字符串中所有匹配子字符串的列表。
finditer()函数
findall() 函数返回匹配给定模式的所有子字符串的列表。如果我们想要访问子字符串的匹配对象来找到它们的跨度,我们不能使用findall() 函数来完成。为此,您可以使用finditer()功能。
finditer() 函数将一个 regex 模式作为其第一个输入参数,将一个字符串作为其第二个输入参数。执行后,它返回一个 iterable 对象,该对象包含非重叠模式匹配的 match 对象。您可以在下面的示例中观察到这一点。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="AA"
output=re.finditer(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:")
for match_object in output:
print("Text:",match_object.group(), "Span:",match_object.span())
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: AA
The output is:
Text: AA Span: (2, 4)
Text: AA Span: (4, 6)
Text: AA Span: (11, 13)
Text: AA Span: (17, 19)
Text: AA Span: (42, 44)
在上面的例子中,finditer() 函数返回匹配子字符串的匹配对象列表。我们已经使用group() 和span()方法获得了匹配的子字符串的文本和位置。
split()函数
re 模块中的split()函数用于按照给定的模式将一个字符串分割成子字符串。split() 函数将一个模式作为其第一个输入参数,将一个字符串作为其第二个输入参数。执行后,它在发现模式的位置拆分给定的字符串,并返回如下所示的子字符串列表。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="AA"
output=re.split(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: AA
The output is: ['AC', '', 'BCBCB', 'ABAC', 'DABCABDBACABACDBADBCACB', 'BCDDDDCABACBCDA']
正如您在上面的示例中所看到的,原始字符串是从出现两个 a 的位置拆分出来的。拆分后,剩余子字符串的列表由split()函数返回。
如果模式出现在字符串的开头,那么由split()函数返回的列表也包含一个空字符串。您可以在下面的示例中观察到这一点。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="AC"
output=re.split(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: AC
The output is: ['', 'AAAABCBCBAAAB', 'AADABCABDB', 'AB', 'DBADBC', 'BAABCDDDDCAB', 'BCDA']
如果输入字符串不包含给定的模式,则由split()函数返回的列表包含输入字符串作为其唯一的元素,如下例所示。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="AY"
output=re.split(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: AY
The output is: ['ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA']
如您所见,输入字符串中没有出现"AY"。因此,输入字符串没有被分割,输出列表只包含一个字符串。
sub()函数
re 模块中的sub()函数用于在 Python 中用另一个字符串替换一个子字符串。sub()函数的语法如下。
re.sub(old_pattern, new_pattern, input_string)
re.sub()函数接受三个输入参数。执行后,它将input_string中的old_pattern替换为new_pattern,并返回修改后的字符串,如下例所示。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="A"
replacement="S"
output=re.sub(pattern,replacement,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The new pattern is:",replacement)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: A
The new pattern is: S
The output is: SCSSSSBCBCBSSSBSCSSDSBCSBDBSCSBSCDBSDBCSCBSSBCDDDDCSBSCBCDS
到目前为止,我们已经讨论了 Python 中的一些正则表达式函数。对于使用 Python 中正则表达式的文本分析,我们还需要了解一些正则表达式工具来创建分析所需的模式。让我们逐一讨论。
建议阅读:如果你对数据挖掘和数据分析感兴趣,你可以阅读这篇关于使用 Python 中的 sklearn 模块进行 k-means 聚类的文章。
Python 中用于文本分析的正则表达式模式和字符类
使用 python 执行文本分析时,您可能需要同时检查两个或更多模式。在这种情况下,您可以使用字符类。
在 Python 中使用正则表达式匹配单个模式
例如,如果给你一个包含学生成绩的字符串,你需要检查字符串中 A 的数量,你可以使用如下所示的findall() 函数和字符 ‘A’ 模式来完成。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="A"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: A
The output is: ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']
这里,字符"A"的所有出现都由findall()函数返回。
在 Python 中使用正则表达式匹配多个模式
现在,假设您需要检查字符串中有多少个 A 或 B,您不能在findall()函数中使用模式“AB”。模式“AB”匹配紧跟着 b 的 A
为了匹配 A 或 B,我们将使用字符类。因此,我们将使用模式“[AB]”。在这里,当我们将AB放在模式字符串内的方括号中时,它表现为一个集合。因此,模式匹配 A 或 b。但是,它不会匹配 AB。您可以在下面的示例中观察到这一点。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="[AB]"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: [AB]
The output is: ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'A', 'A', 'A', 'B', 'A', 'A', 'A', 'A', 'B', 'A', 'B', 'B', 'A', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'A', 'B', 'A', 'B', 'A', 'B', 'A']
在上面的例子中, findall()函数搜索 A 或 B 并返回所有匹配的子字符串。
现在,你可以找到模式“A”、“B”和“AB”。如果你必须找到 A 后面跟着 B 或者 C 呢?换句话说,你必须匹配模式 “AB” 或 “AC”。在这种情况下,我们可以使用“[A][BC]”模式。这里,我们将 A 放在一个单独的方括号中,因为它是一个强制字符。在下面的方括号中,我们把 BC 放了出来,在模式中只考虑其中的一个字符。因此,模式将匹配 AB 以及 AC。您可以在下面的示例中观察到这一点。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="[A][BC]"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: [A][BC]
The output is: ['AC', 'AB', 'AB', 'AC', 'AB', 'AB', 'AC', 'AB', 'AC', 'AC', 'AB', 'AB', 'AC']
您也可以使用管道操作符|来创建模式“AB|AC”。这里,管道操作符作为 or 操作符工作,模式将匹配 AB 和 AC。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="AB|AC"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: AB|AC
The output is: ['AC', 'AB', 'AB', 'AC', 'AB', 'AB', 'AC', 'AB', 'AC', 'AC', 'AB', 'AB', 'AC']
使用 Python 中的正则表达式匹配除一个模式之外的所有模式
假设您想要查找输入字符串中除 A 级之外的所有等级。在这种情况下,我们将在字符 A 之前的方括号中引入脱字符,如“[^A]”所示。此模式将匹配除 A 之外的所有模式,如下所示。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="[^A]"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: [^A]
The output is: ['C', 'B', 'C', 'B', 'C', 'B', 'B', 'C', 'D', 'B', 'C', 'B', 'D', 'B', 'C', 'B', 'C', 'D', 'B', 'D', 'B', 'C', 'C', 'B', 'B', 'C', 'D', 'D', 'D', 'D', 'C', 'B', 'C', 'B', 'C', 'D']
记住模式“^A”不会给出相同的结果。当方括号中没有插入符号字符时,这意味着模式应该从紧跟插入符号字符的字符开始。因此,模式“^A” 将检查以 a 开头的模式。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="^A"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: ^A
The output is: ['A']
使用正则表达式量词根据模式中的字符数匹配模式
如果你想匹配两个连续的 A,你可以使用模式“AA”或“[A][A]”。如果您必须在一个大文本中匹配 100 个连续的 A 会怎么样?在这种情况下,您不能手动创建 100 个字符的模式。在这种情况下,正则表达式量词可以帮助您。
正则表达式量词用于指定模式中连续字符的数量。表示为pattern{m}。这里,模式是我们正在寻找的模式,m 是该模式的重复次数。例如,您可以使用量词来表示连续的 A,如下所示。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="A{4}"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: A{4}
The output is: ['AAAA']
在上面的例子中,您需要确保花括号中不包含任何空格字符。它应该只包含用作量词的数字。否则,你得不到想要的结果。您可以在下面的示例中观察到这一点。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA"
pattern="A{4 }"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBADBCACBAABCDDDDCABACBCDA
The pattern is: A{4 }
The output is: []
现在,假设您想要匹配任何最小为 2 个 A,最大为 6 个 A 的模式。在这种情况下,您可以使用语法模式{m,n}来表示该模式。这里,m 是模式连续出现的下限,n 是上限。
例如,您可以使用模式“A{2,6}”匹配 2 到 6 个 A,如下例所示。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBAAAAAAADBCACBAABCDDDDCABACBCDA"
pattern="A{2,6}"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBAAAAAAADBCACBAABCDDDDCABACBCDA
The pattern is: A{2,6}
The output is: ['AAAA', 'AAA', 'AA', 'AAAAAA', 'AA']
同样,您需要确保括号内没有空格。否则,程序不会给出预期的结果。
你也可以一次重复使用不同的模式。例如,如果您想匹配 2 到 5 A,然后是 1 到 2 B,您可以使用如下所示的模式“A{2,5}B{1,2}”。
import re
text="ACAAAABCBCBAAABACAADABCABDBACABACDBAAAAAAADBCACBAABCDDDDCABACBCDA"
pattern="A{2,5}B{1,2}"
output=re.findall(pattern,text)
print("The text is:",text)
print("The pattern is:",pattern)
print("The output is:",output)
输出:
The text is: ACAAAABCBCBAAABACAADABCABDBACABACDBAAAAAAADBCACBAABCDDDDCABACBCDA
The pattern is: A{2,5}B{1,2}
The output is: ['AAAAB', 'AAAB', 'AAB']
结论
在本文中,我们讨论了 Python 中用于文本分析的一些正则表达式函数。要了解更多关于 python 中的文本分析,您可以阅读这篇关于删除字符串中出现的所有字符的文章。你可能也会喜欢这篇关于用 Python 理解列表的文章。
请继续关注更多内容丰富的文章。
快乐学习!
使用 Python 分割文本文件的最快方法
原文:https://www.pythonforbeginners.com/files/the-fastest-way-to-split-a-text-file-using-python
Python 是世界上最流行的编程语言之一。它受欢迎的一个原因是 Python 使得处理数据变得容易。
从文本文件中读取数据是 Python 中的例行任务。在这篇文章中,我们将看看使用 Python 读取和分割文本文件的最快方法。拆分数据会将文本转换为列表,使其更易于处理。
我们还将介绍 Python 中拆分文本文件的一些其他方法,并解释这些方法如何以及何时有用。
在下面的例子中,我们将看到 Python 如何帮助我们掌握阅读文本数据。利用 Python 的许多内置函数将简化我们的任务。
介绍 split()方法
在 Python 中拆分文本的最快方法是使用 split() 方法。这是一个内置的方法,可用于将字符串分成各个部分。
split()方法将返回一个字符串中的元素列表。默认情况下,Python 使用空格来分割字符串,但是您可以提供一个分隔符并指定使用什么字符。
例如,逗号(,)常用来分隔字符串数据。逗号分隔值(CSV)文件就是这种情况。无论您选择什么作为分隔符,Python 都将使用它来分割字符串。
用 split()方法拆分文本文件
在第一个例子中,我们有一个雇员数据的文本文件,包括雇员的姓名、电话号码和职业。我们需要编写一个 Python 程序来读取这些随机生成的信息,并将数据分成列表。
employee _ data . txt
Lana Anderson 485-3094-88 电工
Elian Johnston 751-5845-87 室内设计师
Henry Johnston 777-6561-52 天文学家
Dale Johnston 248-1843-09 记者
Luke Owens 341-7471-63 教师
Amy Perry 494-3532-17 电工
Chloe Baker 57
在使用 Python with 语句打开数据文件后,我们可以使用 for 循环遍历文件内容。读取数据后,使用 split()方法将文本分成单词。
在我们的例子中,文本使用空格分隔,这是 split()方法的默认行为。
示例 1:使用 Python 拆分员工数据
with open("employee_data.txt",'r') as data_file:
for line in data_file:
data = line.split()
print(data)
输出
['Lana', 'Anderson', '485-3094-88', 'Electrician']
['Elian', 'Johnston', '751-5845-87', 'Interior', 'Designer']
['Henry', 'Johnston', '777-6561-52', 'Astronomer']
['Dale', 'Johnston', '248-1843-09', 'Journalist']
['Luke', 'Owens', '341-7471-63', 'Teacher']
['Amy', 'Perry', '494-3532-17', 'Electrician']
['Chloe', 'Baker', '588-7165-01', 'Interior', 'Designer']
用逗号分割字符串
我们为 split()方法提供了一个可选的分隔符来指定用哪个字符来分割字符串。默认分隔符是空白。
在下一个例子中,我们将使用逗号来分割从文件中读取的测试分数数据。
grades.txt
珍妮特,100,50,69
托马斯,99,76,100
凯特,102,78,65
示例 2:用逗号分割分数
with open("grades.txt",'r') as file:
for line in file:
grade_data = line.strip().split(',')
print(grade_data)
这里使用了 strip() 方法来删除行尾的换行符(\n)。
输出
['Janet', '100', '50', '69']
['Thomas', '99', '76', '100']
['Kate', '102', '78', '65']
用 splitlines()拆分文本文件
方法的作用是获取一个文本文件中的行列表。在接下来的例子中,我们将假设我们运行一个专门面向戏剧公司的网站。我们从文本文件中读取脚本数据,并将其推送到公司的网站上。
罗密欧,罗密欧,为什么你是罗密欧?
否定你的父亲,拒绝你的名字。
或者如果你不愿意,只要发誓做我的爱人,我就不再是凯普莱特家族的人了。
我们可以读取文件,并用 splitlines()方法将这些行分割成一个列表。然后,可以使用 for 循环来打印文本数据的内容。
示例 3:使用 splitlines()读取文本文件
with open("juliet.txt",'r') as script:
speech = script.read().splitlines()
for line in speech:
print(line)
使用生成器拆分文本文件
在 Python 中,生成器是一个特殊的例程,可用于创建数组。生成器类似于返回数组的函数,但它一次返回一个元素。
生成器使用 yield 关键字。当 Python 遇到 yield 语句时,它存储函数的状态,直到稍后再次调用生成器。
在下一个例子中,我们将使用一个生成器来读取莎士比亚的罗密欧与朱丽叶中罗密欧的著名演讲的开头。使用 yield 关键字可以确保在每次迭代中保存 while 循环的状态。这在处理大文件时会很有用。
romeo.txt
但是柔柔,那边窗户透进来的是什么光?
是东方,朱丽叶是太阳。
起来,美丽的太阳,杀死嫉妒的月亮,
她已经病入膏肓,悲伤苍白
你,她的女仆,远比她美丽。
示例 4:使用生成器拆分文本文件
def generator_read(file_name):
file = open(file_name,'r')
while True:
line = file.readline()
if not line:
file.close()
break
yield line
file_data = generator_read("romeo.txt")
for line in file_data:
print(line.split())
用列表理解读取文件数据
Python 列表理解为处理列表提供了一个优雅的解决方案。我们可以利用较短的语法来编写带有列表理解的代码。此外,列表理解语句通常更容易阅读。
在前面的例子中,我们不得不使用 for 循环来读取文本文件。我们可以使用列表理解将 for 循环换成一行代码。
列表理解语法:
my_list =【表达式】for 元素inList**
一旦通过列表理解获得了数据,我们就使用 split()方法来分离这些行,并将它们添加到一个新的列表中。
使用前一个例子中的同一个 romeo.txt 文件,让我们看看 list comprehension 如何提供一种更优雅的方法来分割 Python 中的文本文件。
示例 5:使用列表理解来读取文件数据
with open("romeo.txt",'r') as file:
lines = [line.strip() for line in file]
for line in lines:
print(line.split())
将一个文本文件分割成多个较小的文件
如果我们有一个大文件,我们想分裂成较小的文件呢?我们使用 for 循环和切片在 Python 中分割一个大文件。
通过列表切片,我们告诉 Python 我们想要处理给定列表中特定范围的元素。这是通过提供切片的起点和终点来完成的。
在 Python 中,列表可以用冒号分割。在下面的例子中,我们将使用列表切片将一个文本文件分割成多个更小的文件。
用列表切片分割文件
可以使用 Python 列表切片来分割列表。为此,我们首先使用 readlines() 方法读取文件。接下来,文件的上半部分被写入一个名为 romeo_A.txt 的新文件。我们将在这个 for 循环中使用列表切片将原始文件的前半部分写入一个新文件。
使用第二个 for 循环,我们将把剩余的文本写到另一个文件中。为了执行切片,我们需要使用 len() 方法来查找原始文件中的总行数。
最后, int() 方法用于将除法结果转换为整数值。
示例 6:将单个文本文件拆分成多个文本文件
with open("romeo.txt",'r') as file:
lines = file.readlines()
with open("romeo_A.txt",'w') as file:
for line in lines[:int(len(lines)/2)]:
file.write(line)
with open("romeo_B.txt",'w') as file:
for line in lines[int(len(lines)/2):]:
file.write(line)
在与 romeo.txt 相同的目录下运行该程序将创建以下文本文件。
romeo_A.txt
但是柔柔,那边窗户透进来的是什么光?
是东方,朱丽叶是太阳。
罗密欧 _B.txt
起来吧,美丽的太阳,杀死嫉妒的月亮,
她已经病入膏肓,悲伤苍白
你,她的女仆,远比她美丽。
相关职位
我们已经看到了如何使用 split()方法来分割文本文件。此外,我们的示例展示了 split()如何与 Python 生成器和 list comprehension 配合使用,以更优雅地读取大文件。
利用 Python 的许多内置方法,如 split()和 readlines(),我们可以更快地处理文本文件。使用这些工具将节省我们的时间和精力。
如果你真的想掌握 Python,花些时间学习如何使用这些方法来准备你自己的解决方案是个好主意。
如果你想学习更多关于 Python 编程的知识,请访问下面的 Python 初学者教程。
- Python 注释如何决定你程序的成败
- 用 Python 列表理解加速您的代码
Python 中的翻译表
原文:https://www.pythonforbeginners.com/basics/translation-table-in-python
Python 为我们提供了操作字符串的不同方式。在本文中,我们将讨论转换表,并使用它在 python 中用字符串中的另一个字符替换一个字符。
什么是翻译表?
简单地说,翻译表是一个字符到另一个字符的映射。在处理字符串时,我们可能需要用字符串中的另一个字符替换一个字符。在这种情况下,我们可以使用转换表来确定哪个字符必须被哪个字符替换。
您可以将转换表想象成一个字典,其中的键是最初出现在字符串中的字符,值是将替换现有字符的字符。
现在,让我们看看如何用 python 创建一个翻译表。
如何创建翻译表?
Python 为我们提供了 maketrans()函数,用它我们可以创建一个翻译表。maketrans()函数接受三个参数并返回一个转换表。第一个参数是包含需要替换的字符的字符串。第二个输入参数是包含新字符的字符串。第三个也是可选的参数是一个字符串,它包含需要从任何字符串中删除的字符。maketrans()函数的语法如下:
maketrans(old_characters,new_characters,characters_to_delete). 在这里,
- old_characters 是包含需要替换的字符的字符串。
- new_characters 是一个字符串,它包含的字符将被用来代替 old_characters 中的字符。理想情况下,新字符的长度应该等于旧字符。这样, old_characters 中的每个字符都会映射到 new_character 中相应位置的字符上。
- characters_to_delete 包含将从任何字符串中删除的字符。
我们可以用 python 创建一个翻译表,如下例所示。
import string
input_string = """This is PythonForBeginners.com.
Here, you can read python tutorials for free."""
translation_table = input_string.maketrans("abcdefghijklmnopqrstupwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
print("The translation table is:")
print(translation_table)
输出:
The translation table is:
{97: 65, 98: 66, 99: 67, 100: 68, 101: 69, 102: 70, 103: 71, 104: 72, 105: 73, 106: 74, 107: 75, 108: 76, 109: 77, 110: 78, 111: 79, 112: 86, 113: 81, 114: 82, 115: 83, 116: 84, 117: 85, 119: 87, 120: 88, 121: 89, 122: 90}
这里,字符 A 到 Z 和 A 到 Z 的 ASCII 值用于创建翻译表。转换表的关键字是小写字母的 ASCII 值,对应的值是大写字母的 ASCII 值。我们可以使用这个转换表将小写字符替换为大写字符。我们没有指定任何必须删除的字符。
翻译表怎么用?
我们使用翻译表和 translate()方法来替换字符串中的字符。在字符串上调用 translate()方法时,它将翻译表作为输入,并根据翻译表替换原始字符串中的字符。你可以从下面的例子中理解这一点。
import string
input_string = """This is PythonForBeginners.com.
Here, you can read python tutorials for free."""
translation_table = input_string.maketrans("abcdefghijklmnopqrstupwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ")
new_string = input_string.translate(translation_table)
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
输出:
The original string is:
This is PythonForBeginners.com.
Here, you can read python tutorials for free.
Output String is:
THIS IS PYTHONFORBEGINNERS.COM.
HERE, YOU CAN READ VYTHON TUTORIALS FOR FREE.
这里,我们使用上一个示例中创建的转换表将所有小写字符替换为大写字符。
结论
在本文中,我们讨论了 python 中的翻译表。我们还看到了如何使用 maketrans()方法和 translate()方法来替换字符串中的字符。要了解更多关于 python 编程的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于 Python 中链表的文章。
Python 中的树形数据结构
原文:https://www.pythonforbeginners.com/data-structures/tree-data-structure-in-python
就特性和数据结构而言,Python 是一种非常丰富的语言。它有很多内置的数据结构,比如 python 字典、列表、元组、集合、frozenset 等等。除此之外,我们还可以使用类创建自己的自定义数据结构。在本文中,我们将学习 Python 中的二叉树数据结构,并尝试使用一个例子来实现它。
Python 中的树型数据结构是什么?
树是一种数据结构,其中数据项使用引用以分层方式连接。每棵树由一个根节点组成,从这个根节点我们可以访问树的每个元素。从根节点开始,每个节点包含零个或多个与其连接的节点作为子节点。一个简单的二叉树可以描述如下图所示。

Tree Data Structure
树数据结构的一部分
树由根节点、叶节点和内部节点组成。每个节点通过一个称为边的引用连接到它的智利。
根节点:根节点是一棵树的最顶层节点。它总是创建树时创建的第一个节点,我们可以从根节点开始访问树的每个元素。在上面的例子中,包含元素 50 的节点是根节点。
父节点:任何节点的父节点都是引用当前节点的节点。在上面的示例中,50 是 20 和 45 的父级,20 是 11、46 和 15 的父级。同样,45 是 30 和 78 的父代。
子节点:父节点的子节点是父节点使用引用指向的节点。在上面的例子中,20 和 45 是 50 的孩子。节点 11、46 和 15 是 20 和 30 的子节点,节点 78 是 45 的子节点。
边:父节点通过其连接到子节点的引用称为边。在上面的例子中,连接任意两个节点的每个箭头都是一条边。
叶节点:这些是树中没有子节点的节点。在上面的例子中,11、46、15、30 和 78 是叶节点。
内部节点:内部节点是指至少有一个子节点的节点。在上面的例子中,50、20 和 45 是内部节点。
什么是二叉树?
二叉树是一种树形数据结构,其中每个节点最多可以有 2 个子节点。这意味着二叉树中的每个节点可以有一个、两个或没有子节点。二叉树中的每个节点都包含数据和对其子节点的引用。这两个孩子根据他们的位置被命名为左孩子和右孩子。二叉树中节点的结构如下图所示。

Node of a Binary Tree
我们可以使用如下的类在 python 中定义如上所示结构的节点。
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild=None
这里,节点的构造函数将数据值作为输入,创建 BinaryTreeNode 类型的对象,将数据字段初始化为给定的输入,并将对子节点的引用初始化为 None。稍后可以将子节点分配给节点。下图显示了一个二叉树的例子。

Binary Tree Data Structure
我们可以用 python 实现上面的二叉树,如下所示。
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
node1 = BinaryTreeNode(50)
node2 = BinaryTreeNode(20)
node3 = BinaryTreeNode(45)
node4 = BinaryTreeNode(11)
node5 = BinaryTreeNode(15)
node6 = BinaryTreeNode(30)
node7 = BinaryTreeNode(78)
node1.leftChild = node2
node1.rightChild = node3
node2.leftChild = node4
node2.rightChild = node5
node3.leftChild = node6
node3.rightChild = node7
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:
45
Node is:
20
left child of the node is:
11
right child of the node is:
15
Node is:
45
left child of the node is:
30
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:
15
left child of the node is:
None
right child of the node is:
None
Node is:
30
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
结论
在本文中,我们讨论了 Python 中的树形数据结构和二叉树数据结构。要了解更多关于 Python 中数据结构的知识,可以阅读这篇关于 python 中链表的文章。
Python 中的元组字符串到元组
原文:https://www.pythonforbeginners.com/basics/tuple-string-to-tuple-in-python
将数据从一种形式转换成另一种形式是一项单调乏味的任务。在本文中,我们将讨论在 python 中将元组字符串转换为元组的两种方法。
如何在 Python 中将元组字符串转换成元组
假设给我们一个字符串形式的元组,如下所示。
myStr = "(1,2,3,4,5)"
现在,我们必须从给定的字符串创建元组(1,2,3,4,5)。为此,我们将首先删除括号和逗号“,” 字符。为此,我们将使用replace()方法用空格替换逗号,用空字符串替换括号。在字符串上调用replace()方法时,将被替换的字符作为第一个输入参数,新字符作为第二个输入参数。我们将使用 replace()方法逐一替换“(”, “)”和 “,”字符,如下所示。
myStr = "(1,2,3,4,5)"
print("The tuple string is:", myStr)
myStr = myStr.replace("(", "")
myStr = myStr.replace(")", "")
myStr = myStr.replace(",", " ")
print("The output string is:", myStr)
输出:
The tuple string is: (1,2,3,4,5)
The output string is: 1 2 3 4 5
现在,我们获得了一个包含由空格分隔的数字的字符串。为了从字符串中获取数字,我们现在将使用split()方法分割字符串。在字符串上调用split() 方法时,该方法将一个字符作为可选的输入参数,并在指定字符处分割字符串后返回一个包含元素的列表。如果我们不给出任何字符作为输入参数,它会在空格处分割字符串。
我们将使用split()方法分割字符串,如下所示。
myStr = "(1,2,3,4,5)"
print("The tuple string is:", myStr)
myStr = myStr.replace("(", "")
myStr = myStr.replace(")", "")
myStr = myStr.replace(",", " ")
myList = myStr.split()
print("The output list is:", myList)
输出:
The tuple string is: (1,2,3,4,5)
The output list is: ['1', '2', '3', '4', '5']
现在,我们已经获得了一个包含所有数字的列表。但是,它们以字符串的形式出现。为了获得一个整数列表,我们将如下使用map()函数和int()函数。
myStr = "(1,2,3,4,5)"
print("The tuple string is:", myStr)
myStr = myStr.replace("(", "")
myStr = myStr.replace(")", "")
myStr = myStr.replace(",", " ")
myList = myStr.split()
myList = list(map(int, myList))
print("The output list is:", myList)
输出:
The tuple string is: (1,2,3,4,5)
The output list is: [1, 2, 3, 4, 5]
由于我们已经获得了整数列表,我们将从列表中创建一个元组,如下所示。
myStr = "(1,2,3,4,5)"
print("The tuple string is:", myStr)
myStr = myStr.replace("(", "")
myStr = myStr.replace(")", "")
myStr = myStr.replace(",", " ")
myList = myStr.split()
myList = list(map(int, myList))
myTuple = tuple(myList)
print("The output tuple is:", myTuple)
输出:
The tuple string is: (1,2,3,4,5)
The output tuple is: (1, 2, 3, 4, 5)
您可以看到,我们已经使用 python 中的 replace()方法、 split()方法和int() 函数将 tuple 字符串转换为 tuple。
使用 Python 中的 eval()函数将元组字符串转换为元组
eval()函数用于计算表达式。它将一个字符串作为输入参数,遍历该字符串,然后返回输出。我们可以使用如下所示的eval()函数直接将 tuple 字符串转换成 tuple。
myStr = "(1,2,3,4,5)"
print("The tuple string is:", myStr)
myTuple = eval(myStr)
print("The output tuple is:", myTuple)
输出:
The tuple string is: (1,2,3,4,5)
The output tuple is: (1, 2, 3, 4, 5)
结论
在本文中,我们讨论了在 python 中将元组字符串转换为元组的两种方法。要了解更多关于字符串的知识,您可以阅读这篇关于 python 中字符串格式化的文章。你可能也会喜欢这篇关于理解 python 中的 T2 的文章。
使用 Python 进行 Tweet 搜索
原文:https://www.pythonforbeginners.com/python-on-the-web/tweet-search-with-python
概观
Twitter 的 API 是基于 REST 的,将返回 XML 或 JSON 格式的结果,以及 RSS 和 ATOM 提要格式的结果。任何客户端都可以访问公共时间轴,但所有其他 Twitter 方法都需要认证。
关于这个剧本
该计划是有据可查的,应该是直截了当的。打开一个文本编辑器,复制并粘贴下面的代码。
将文件另存为:“tweet_search.py”并退出编辑器。
入门指南
让我们来看看下面这个叫做 tweet_search.py 的程序
#!/usr/bin/python
import json
import sys
import urllib2
import os
usage = """
Usage: ./tweet_search.py 'keyword'
e.g ./tweet_search.py pythonforbeginners
Use "+" to replace whitespace"
e.g ./tweet_search.py "python+for+beginners"
"""
# Check that the user puts in an argument, else print the usage variable, then quit.
if len(sys.argv)!=2:
print (usage)
sys.exit(0)
# The screen name in Twitter, is the screen name of the user for whom to return results for.
# Set the screen name to the second argument
screen = sys.argv[1]
# Open the twitter search URL the result will be shown in json format
url = urllib2.urlopen("http://search.twitter.com/search.json?q="+screen)
#convert the data and load it into json
data = json.load(url)
#to print out how many tweets there are
print len(data), "tweets"
# Start parse the tweets from the result
# Get only text
for tweet in data["results"]:
print tweet["text"]
# Get the status and print out the contents
for status in data['results']:
print "(%s) %s" % (status["created_at"], status["text"])
它是如何工作的?
让我们分解这个脚本,看看它做了什么。
该脚本从导入我们将需要的模块开始
第 3-6 行
import json
import sys
import urllib2
import os
我们创建一个用法变量来解释如何使用这个脚本。
**Line 8-14** usage = """ Usage: ./tweet_search.py 'keyword' e.g ./tweet_search.py pythonforbeginners Use "+" to replace whitespace" e.g ./tweet_search.py "python+for+beginners" """
在第 16 行,我们检查用户是否输入了参数,否则打印用法变量,然后退出。
if len(sys.argv)!=2:
print (usage)
sys.exit(0)
第 21-24 行将 Twitter 屏幕名称设置为第二个参数。
screen = sys.argv[1]
第 27 行打开 twitter 搜索 URL,结果将以 json 格式显示。
url = urllib2.urlopen("http://search.twitter.com/search.json?q="+screen)
第 30 行转换数据并将其加载到 json 中
data = json.load(url)
在第 33 行,我们打印出了推文的数量
print len(data), "tweets"
从第 38 行开始,我们开始从结果中解析 tweets
for tweet in data["results"]:
print tweet["text"]
我们在这个脚本中做的最后一件事是获取状态并打印出内容(第 42 行)
for status in data['results']:
print "(%s) %s" % (status["created_at"], status["text"])
一行一行地检查脚本,看看它做了什么。一定要看着它,试着去理解它。
Python 中的 TypeError
原文:https://www.pythonforbeginners.com/basics/typeerror-in-python
用 Python 编程的时候有没有试过用字符串除整数?如果是,您可能会得到类似“TypeError:不支持/:“int”和“str”的操作数类型”的错误消息。在本文中,我们将讨论 Python 中的这个 TypeError 异常。我们还将研究发生 TypeError 异常的不同情况,以及如何避免它们。
Python 中什么是 TypeError?
TypeError 是 Python 编程语言中的一个异常,当操作中对象的数据类型不合适时就会发生。例如,如果试图用字符串除一个整数,则整数和字符串对象的数据类型将不兼容。因此,Python 解释器将引发一个 TypeError 异常,如下例所示。
myInt = 100
myStr = "10"
myResult = myInt / myStr
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = myInt / myStr
TypeError: unsupported operand type(s) for /: 'int' and 'str'
让我们再举一个例子,假设我们想要连接两个列表。我们可以使用+操作符来实现,如下所示。
list1 = [1, 2, 3]
list2 = [4, 5, 6]
myResult = list1 + list2
print("First list is:", list1)
print("second list is:", list2)
print("Resultant list is:", myResult)
输出:
First list is: [1, 2, 3]
second list is: [4, 5, 6]
Resultant list is: [1, 2, 3, 4, 5, 6]
现在假设我们传递一个元组来代替第二个列表。这里,列表和元组数据类型在串联运算符中是不兼容的。因此,python 解释器将引发如下所示的 TypeError 异常。
list1 = [1, 2, 3]
list2 = (4, 5, 6)
myResult = list1 + list2
print("First list is:", list1)
print("second list is:", list2)
print("Resultant list is:", myResult)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = list1 + list2
TypeError: can only concatenate list (not "tuple") to list
看看这些例子,我们可以说,如果一个操作中不同对象的数据类型不兼容,因而不合适,那么 TypeError 就是 python 解释器引发的一个异常。
现在让我们来看一些可能发生 TypeError 异常的情况。
Python 中什么时候会出现 TypeError 异常?
异常迫使程序提前终止。同样,没有人希望他们的程序中出现异常。但是,我们无法控制用户如何将输入传递给程序。可能有各种可能发生 TypeError 异常的情况。
让我们来看看其中的一些。
使用内置函数时可能会出现 TypeError 异常
所有内置函数都接受特定类型的输入参数。例如,集合中的 add()方法只接受不可变的对象,如整数、字符串、元组、浮点数等作为输入参数。如果我们试图给一个像 list 这样的可变对象作为 add()方法的输入,它将引发 TypeError,并显示一条消息"type error:unhashable type:' list '"如下所示。
mySet = {1, 2, 3}
myList = [4, 5, 6]
mySet.add(myList)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
mySet.add(myList)
TypeError: unhashable type: 'list'
在两种不兼容的数据类型之间执行操作时,可能会出现 TypeError 异常
我们知道,在 Python 中,数学运算或位运算只针对某些数据类型定义。例如,我们可以将一个整数加到一个整数或浮点数上。另一方面,我们不能将字符串对象添加到整数中。向 string 对象添加整数将导致 TypeError,并显示消息" TypeError:不支持+: 'int '和' str' "的操作数类型,如下所示。
myInt = 100
myStr = "200"
myResult = myInt + myStr
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
myResult = myInt + myStr
TypeError: unsupported operand type(s) for +: 'int' and 'str'
同样,所有的数学运算只允许在特定的数据类型之间进行。如果试图对具有不兼容数据类型的对象执行数学运算,将会发生 TypeError。
如果我们谈论按位运算,我们可以对整数执行按位运算,但不能对字符串执行。例如,我们可以将一个整数右移两位,如下所示。
myInt = 100
myResult = myInt >> 2
print("The given Integer is:", myInt)
print("Result is:", myResult)
输出:
The given Integer is: 100
Result is: 25
另一方面,如果我们试图对一个字符串执行右移操作,它将引发 TypeError,并显示消息" TypeError:不支持的操作数类型用于> > : 'str '和' int' ",如下所示。
myStr = "100"
myResult = myStr >> 2
print("The given String is:", myStr)
print("Result is:", myResult)
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
myResult = myStr >> 2
TypeError: unsupported operand type(s) for >>: 'str' and 'int'
因此,您可以看到,对不兼容的数据类型执行数学或位运算会导致程序中出现 TypeError 异常。
调用不可调用的对象时可能会出现 TypeError 异常
在 python 中,函数、方法以及所有在类定义中实现了 call()方法的对象都是可调用的。我们可以像调用函数或方法一样调用任何可调用的对象。
另一方面,如果我们调用一个不可调用的对象,比如 integer,它将引发一个 TypeError 异常,并显示消息"type error:' int ' object is not callable",如下所示。
myInt = 100
myInt()
输出:
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 2, in <module>
myInt()
TypeError: 'int' object is not callable
如何避免 Python 中的 TypeError 异常?
程序中的错误是不可避免的。但是,您总是可以最小化错误的发生。要最大限度地减少 TypeError 异常,可以使用以下准则。
- 每当您试图使用内置方法或函数时,请务必阅读其文档。这将帮助您理解函数的输入和输出。了解输入和输出将有助于避免程序中的类型错误异常。
- 在执行数学或按位运算时,可以事先检查操作数的数据类型。这将帮助您避免对不兼容的数据类型执行数学或位运算。因此,您将能够避免 TypeError 异常。
- 给程序中的变量、函数、类和方法起适当的名字。这将帮助您避免调用不可调用的对象。因此,您将能够避免 TypeError 异常。
结论
在本文中,我们讨论了 TypeError 异常、其原因以及如何避免它们。您还可以使用 python try-except 块来处理这些异常。但是,我会建议您避免异常,而不是在异常发生后处理它。
要了解更多关于 python 编程的知识,您可以阅读这篇关于 Python 中的字符串操作的文章。你可能也会喜欢这篇关于 Python IndexError 的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
Python 中列表的联合
原文:https://www.pythonforbeginners.com/basics/union-of-lists-in-python
在 python 中,我们几乎在每个程序中都使用列表。有时,我们可能需要合并两个列表。需要合并的列表可能有一些共同的元素。为了避免在结果列表中包含重复的元素,我们可以执行给定列表的并集。在本文中,我们将讨论列表上的联合操作意味着什么,以及如何在 python 中执行两个列表的联合。
如何在 Python 中执行列表的并集?
要在 python 中执行两个列表的联合,我们只需创建一个输出列表,它应该包含来自两个输入列表的元素。例如,如果我们有list1=[1,2,3,4,5,6]和list2=[2,4,6,8,10,12],list1和list2的联合将是 [1,2,3,4,5,6,8,10,12]。您可以观察到输出列表的每个元素要么属于list1要么属于list2。换句话说,list1 和 list2 中的每个元素都出现在输出列表中。
我们可以使用各种方法在 python 中执行列表的联合。让我们逐一讨论。
Python 中使用 For 循环的列表联合
为了使用 for 循环执行列表的联合,我们将首先创建一个名为newList的空列表来存储输出列表的值。之后,我们将使用extend()方法将第一个输入列表的所有元素添加到newList。现在,我们必须将第二个输入列表中还没有的元素添加到newList中。为此,我们将遍历第二个列表的每个元素,并检查它是否存在于newList中。如果元素还没有出现在newList中,我们将使用append()方法将元素附加到newList中。遍历完第二个输入列表后,我们将得到包含两个输入列表的并集的列表作为newList。您可以在下面的示例中观察到这一点。
list1 = [1, 2, 3, 4, 5, 6]
print("First list is:", list1)
list2 = [2, 4, 6, 8, 10, 12]
print("Second list is:", list2)
newList = []
newList.extend(list1)
for element in list2:
if element not in newList:
newList.append(element)
print("Union of the lists is:", newList)
输出:
First list is: [1, 2, 3, 4, 5, 6]
Second list is: [2, 4, 6, 8, 10, 12]
Union of the lists is: [1, 2, 3, 4, 5, 6, 8, 10, 12]
如果允许您修改输入列表,您可以优化上面的方法。为了优化程序,您可以简单地检查第二个输入列表中的元素是否出现在第一个输入列表中,或者不使用 for 循环。如果元素不存在,我们可以将该元素追加到第一个输入列表中。在执行 for 循环后,我们将获得第一个输入列表中两个列表的并集,如下所示。
list1 = [1, 2, 3, 4, 5, 6]
print("First list is:", list1)
list2 = [2, 4, 6, 8, 10, 12]
print("Second list is:", list2)
for element in list2:
if element not in list1:
list1.append(element)
print("Union of the lists is:", list1)
输出:
First list is: [1, 2, 3, 4, 5, 6]
Second list is: [2, 4, 6, 8, 10, 12]
Union of the lists is: [1, 2, 3, 4, 5, 6, 8, 10, 12]
或者,您可以将列表的并集存储在第二个输入列表中,如下所示。
list1 = [1, 2, 3, 4, 5, 6]
print("First list is:", list1)
list2 = [2, 4, 6, 8, 10, 12]
print("Second list is:", list2)
for element in list1:
if element not in list2:
list2.append(element)
print("Union of the lists is:", list2)
输出:
First list is: [1, 2, 3, 4, 5, 6]
Second list is: [2, 4, 6, 8, 10, 12]
Union of the lists is: [2, 4, 6, 8, 10, 12, 1, 3, 5]
Python 中使用集合的列表联合
像并集和交集这样的运算最初是为集合定义的。我们也可以用集合来寻找 python 中两个列表的并集。要使用集合对列表执行联合操作,可以将输入列表转换为集合。之后,您可以使用union()方法执行集合并集操作。最后,您可以将输出集转换回列表,如下所示。
list1 = [1, 2, 3, 4, 5, 6]
print("First list is:", list1)
list2 = [2, 4, 6, 8, 10, 12]
print("Second list is:", list2)
set1 = set(list1)
set2 = set(list2)
newList = list(set1.union(set2))
print("Union of the lists is:", newList)
输出:
First list is: [1, 2, 3, 4, 5, 6]
Second list is: [2, 4, 6, 8, 10, 12]
Union of the lists is: [1, 2, 3, 4, 5, 6, 8, 10, 12]
结论
在本文中,我们讨论了如何在 python 中执行列表的联合。想要了解更多关于列表的知识,你可以阅读这篇关于列表理解的文章。你可能也会喜欢这篇关于如何用 python 反转列表的文章。
使用 Pandas fillna 方法填充 NaN 值
原文:https://www.pythonforbeginners.com/basics/use-the-pandas-fillna-method-to-fill-nan-values
在分析数据时处理 NaN 值是一项重要的任务。python 中的 pandas 模块为我们提供了填充 NaN 值的fillna()方法。在本文中,我们将讨论如何使用 pandas fillna 方法在 Python 中填充 NaN 值。
filna()方法
您可以使用fillna() 方法在 pandas 数据帧中填充 NaN 值。它具有以下语法。
DataFrame.fillna(value=None, *, method=None, axis=None, inplace=False, limit=None, downcast=None)
这里,
value参数取替换 NaN 值的值。还可以将一个 python 字典或一个序列传递给 value 参数。这里,字典应该包含作为键的数据帧的列名,以及作为关联值需要填充到列中的值。类似地, pandas series 应该包含数据帧的列名作为索引,包含替换值作为每个索引的关联值。- 如果没有输入给
value参数,则method参数用于填充数据帧中的 NaN 值。如果value参数不为无,则method参数被设置为无。否则,我们可以指定文字“ffill”、“bfill”、“backfill”或“pad”来指定我们想要填充什么值来代替 NaN 值。 axis参数用于指定填充缺失值的轴。如果您想使用 pandas fillna 方法只填充特定的行或列,您可以使用axis参数。为了填充行中的 NaN 值,axis参数被设置为 1 或“columns”。为了将值填充到列中,axis参数被设置为“index”或 0。- 默认情况下,pandas fillna 方法不修改原始数据帧。它在执行后返回一个新的数据帧,要修改调用
fillna()方法的原始数据帧,可以将inplace参数设置为 True。 - 如果指定了
method参数,则limit参数指定向前/向后填充的连续 NaN 值的最大数量。换句话说,如果连续的“南”数超过了limit数,那么这个缺口只能被部分填补。如果未指定method参数,则limit参数取沿整个轴的最大条目数,其中 nan 将被填充。如果不是无,它必须大于 0。 - 如果需要更改值的数据类型,参数
downcast将字典作为映射来决定应该向下转换的数据类型和目标数据类型。
使用 Pandas Fillna 填充整个数据帧中的 Nan 值
要使用 fillna 方法填充 pandas 数据帧中的 NaN 值,需要将 NaN 值的替换值传递给fillna()方法,如下例所示。
import pandas as pd
import numpy as np
x=pd.read_csv("grade2.csv")
print("The original dataframe is:")
print(x)
x=x.fillna(0)
print("The modified dataframe is:")
print(x)
输出:
The original dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
The modified dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 0 0.0 0
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 0 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 0.0 0.0 0 0.0 0
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 0
9 0.0 0.0 0 0.0 0
10 3.0 15.0 Lokesh 88.0 A
在上面的例子中,我们将值 0 传递给了fillna()方法。因此,输入数据帧中的所有 NaN 值都被替换为 0。
这种方法不太实际,因为不同的列有不同的数据类型。因此,我们可以选择在不同的列中填充不同的值来替换空值。
在熊猫的每一列中填入不同的值
除了用相同的值填充所有 NaN 值,还可以用特定的值替换每列中的 NaN 值。为此,我们需要向fillna()方法传递一个字典,该字典包含作为键的列名和作为关联值填充到列中的值。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=pd.read_csv("grade2.csv")
print("The original dataframe is:")
print(x)
x=x.fillna({"Class":1,"Roll":100,"Name":"PFB","Marks":0,"Grade":"F"})
print("The modified dataframe is:")
print(x)
输出:
The original dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
The modified dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 PFB 0.0 F
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 PFB 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 1.0 100.0 PFB 0.0 F
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 F
9 1.0 100.0 PFB 0.0 F
10 3.0 15.0 Lokesh 88.0 A
在上面的例子中,我们将字典{"Class" :1, "Roll": 100, "Name": "PFB", "Marks" : 0, "Grade": "F" }作为输入传递给了fillna() 方法。因此,"Class"列中的 NaN 值被替换为 1,"Roll"列中的 NaN 值被替换为 100,"Name"列中的 NaN 值被替换为"PFB",依此类推。因此,当我们将数据帧的列名作为键并将一个 python 文字作为关联值传递给键时,NaN 值将根据输入字典在数据帧的每一列中被替换。
您也可以选择忽略一些列名,而不是将所有列名作为输入字典中的键。在这种情况下,不考虑替换输入字典中不存在的列中的 NaN 值。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=pd.read_csv("grade2.csv")
print("The original dataframe is:")
print(x)
x=x.fillna({"Class":1,"Roll":100,"Name":"PFB","Marks":0})
print("The modified dataframe is:")
print(x)
输出:
The original dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
The modified dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 PFB 0.0 NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 PFB 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 1.0 100.0 PFB 0.0 NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 1.0 100.0 PFB 0.0 NaN
10 3.0 15.0 Lokesh 88.0 A
在这个例子中,我们没有将输入字典中的"Grade"列传递给fillna()方法。因此,"Grade"列中的 NaN 值不会被任何其他值替换。
仅填充每列中的前 N 个空值
您也可以限制每列中要填充的 NaN 值的数量,而不是在每列中填充所有 NaN 值。为此,您可以将最大数量的值作为输入参数传递给fillna()方法中的limit参数,如下所示。
import pandas as pd
import numpy as np
x=pd.read_csv("grade2.csv")
print("The original dataframe is:")
print(x)
x=x.fillna(0, limit=3)
print("The modified dataframe is:")
print(x)
输出:
The original dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
The modified dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 0 0.0 0
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 0 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 0.0 0.0 0 0.0 0
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 0
9 0.0 0.0 NaN 0.0 NaN
10 3.0 15.0 Lokesh 88.0 A
在上面的例子中,我们已经将limit参数设置为 3。因此,只有每列的前三个 NaN 值被替换为 0。
仅填充每行的前 N 个空值
要仅填充 dataframe 每一行中的前 N 个空值,可以将要填充的最大值作为输入参数传递给 fillna()方法中的limit参数。此外,您需要通过将axis参数设置为 1 来指定您想要填充的行。您可以在下面的示例中观察到这一点。
import pandas as pd
import numpy as np
x=pd.read_csv("grade2.csv")
print("The original dataframe is:")
print(x)
x=x.fillna(0, limit=2,axis=1)
print("The modified dataframe is:")
print(x)
输出:
The original dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
The modified dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 0.0 0.0 NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 0 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 0.0 0.0 NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 0
9 0.0 0.0 NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
在上面的例子中,我们将limit参数设置为 2,将axis参数设置为 1。因此,当执行fillna()方法时,每行只有两个 NaN 值被替换为 0。
熊猫 Fillna 与最后一个有效的观察
您也可以使用现有值填充 NaN 值,而不是指定新值。例如,您可以通过将方法参数设置为如下所示的“ffill”,使用最后一次有效观察来填充空值。
import pandas as pd
import numpy as np
x=pd.read_csv("grade2.csv")
print("The original dataframe is:")
print(x)
x=x.fillna(method="ffill")
print("The modified dataframe is:")
print(x)
输出:
The original dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
The modified dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 Clara 78.0 B
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 Amy 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 3.0 27.0 Aditya 55.0 C
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 B
9 3.0 11.0 Bobby 50.0 B
10 3.0 15.0 Lokesh 88.0 A
在本例中,我们将方法参数设置为"ffill"。因此,每当遇到 NaN 值时,fillna()方法就用同一列中前一个单元格中的非空值填充特定的单元格。
熊猫 Fillna 与下一个有效的观察
您可以通过将method参数设置为“bfill” 来使用下一个有效观测值填充空值,如下所示。
import pandas as pd
import numpy as np
x=pd.read_csv("grade2.csv")
print("The original dataframe is:")
print(x)
x=x.fillna(method="bfill")
print("The modified dataframe is:")
print(x)
输出:
The original dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
The modified dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 Amy 88.0 A
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 Aditya 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 3.0 23.0 Radheshyam 78.0 B
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 A
9 3.0 15.0 Lokesh 88.0 A
10 3.0 15.0 Lokesh 88.0 A
在本例中,我们已经将method参数设置为"bfill"。因此,每当遇到 NaN 值时,fillna()方法就用同一列中下一个单元格中的非空值填充特定的单元格。
熊猫在原地飞
默认情况下,fillna()方法在执行后返回一个新的数据帧。要修改现有的数据帧而不是创建一个新的数据帧,可以在如下所示的fillna()方法中将inplace参数设置为 True。
import pandas as pd
import numpy as np
x=pd.read_csv("grade2.csv")
print("The original dataframe is:")
print(x)
x.fillna(method="bfill",inplace=True)
print("The modified dataframe is:")
print(x)
输出:
The original dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 NaN NaN NaN
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 NaN 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 NaN NaN NaN NaN NaN
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 NaN
9 NaN NaN NaN NaN NaN
10 3.0 15.0 Lokesh 88.0 A
The modified dataframe is:
Class Roll Name Marks Grade
0 2.0 27.0 Harsh 55.0 C
1 2.0 23.0 Clara 78.0 B
2 3.0 33.0 Amy 88.0 A
3 3.0 34.0 Amy 88.0 A
4 3.0 15.0 Aditya 78.0 B
5 3.0 27.0 Aditya 55.0 C
6 3.0 23.0 Radheshyam 78.0 B
7 3.0 23.0 Radheshyam 78.0 B
8 3.0 11.0 Bobby 50.0 A
9 3.0 15.0 Lokesh 88.0 A
10 3.0 15.0 Lokesh 88.0 A
在这个例子中,我们已经在fillna()方法中将 inplace 参数设置为 True。因此,输入数据帧被修改。
结论
在本文中,我们讨论了如何使用 pandas fillna 方法在 Python 中填充 nan 值。
要了解更多关于 python 编程的知识,你可以阅读这篇关于如何对熊猫数据帧进行排序的文章。你可能也会喜欢这篇关于如何从熊猫数据框中删除列的文章。
我希望你喜欢阅读这篇文章。请继续关注更多内容丰富的文章。
快乐学习!
Python 中用户定义的异常
原文:https://www.pythonforbeginners.com/exceptions/user-defined-exceptions-in-python
当我们用 python 为现实生活中的应用程序编写程序时,对程序中变量的取值有许多限制。例如,年龄不能为负值。当一个人输入一个负值的年龄时,程序会显示一条错误信息。但是这些类型的约束不能在 python 程序中自动应用。为了处理这些类型的错误并对值施加约束,我们在 python 中使用用户定义的异常。在这篇文章中,我们将看看在 python 中实现用户定义的异常的不同方法。
python 中用户定义的异常是什么?
python 中用户定义的异常是由程序员创建的,用来对程序中变量的取值施加约束。Python 有许多内置的异常,当程序中出现错误时会引发这些异常。当程序进入不希望的状态时,在显示程序执行过程中发生了哪个内置异常后,程序会自动终止。我们可以通过使用用户定义的异常来强制约束,从而阻止程序进入不希望的状态。
用户定义的异常可以通过显式引发异常、使用 assert 语句或为用户定义的异常定义自定义类来实现。在本文中,我们将逐一研究每种方法。
在条件语句后显式使用 raise 关键字
内置异常由 python 中的程序自动引发,但我们也可以使用 python try except 块和 raise 关键字引发内置异常。通过使用 raise 关键字显式引发内置异常,我们可以在程序中的任何地方使用它们来强制约束变量值。
例如,假设我们必须根据一个人的年龄来计算他的出生年份,我们可以这样做:
age= 10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
输出:
Age is:
10
Year of Birth is:
2011
在这种情况下,程序通过从当前年份中减去年龄给出了正确的输出。现在假设我们在输入中给年龄一个负值,比如-10。
age= -10
print("Age is:")
print(age)
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
输出:
Age is:
-10
Year of Birth is:
2031
当我们为年龄提供一个负数时,程序仍然可以正常工作,但是输出的结果在逻辑上是不正确的,因为没有人能知道他的出生年份。
为了防止这种年份,我们可以检查输入的 age 中给出的值是否为负,然后我们可以使用 raise 关键字强制程序引发一个异常,如下所示。
raise 语句的语法是raise ExceptionName。当出现错误时,except 块中的代码应该处理该异常,否则将导致程序出错。
try:
age= -10
print("Age is:")
print(age)
if age<0:
raise ValueError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except ValueError:
print("Input Correct age.")
输出:
Age is:
-10
Input Correct age.
这里我们可以看到,对于 10 岁的孩子,程序成功地处理了这个案例。让我们检查当给出正确的年龄值时,它是否给出正确的出生年份。
try:
age= 10
print("Age is:")
print(age)
if age<0:
raise ValueError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except ValueError:
print("Input Correct age.")
输出:
Age is:
10
Year of Birth is:
2011
因此,我们可以看到,在 try except 块中使用 raise 语句后,程序在两种情况下都给出了正确的输出。现在我们将看到如何使用 assert 语句来实施相同的约束。
使用断言语句在 python 中实现用户定义的异常
我们可以使用 assert 语句在 python 中实现对变量值的约束。当不满足 assert 语句中给定的条件时,程序在输出中给出AssertionError。
python 中 assert 语句的语法是assert condition,其中condition可以是计算结果为True或False的任何条件语句。当 assert 语句中的条件求值为True时,程序正常工作。当 assert 语句中的条件评估为False时,程序给出AssertionError。
为了强制实施年龄应该大于零的约束,我们可以使用如下程序所示的 assert 语句。
age= 10
print("Age is:")
print(age)
assert age>0
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
输出:
Age is:
10
Year of Birth is:
2011
当年龄输入为负值时,条件将评估为假,程序将因AssertionError而结束。
age= -10
print("Age is:")
print(age)
assert age>0
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
输出:
Age is:
-10
Traceback (most recent call last):
File "<ipython-input-9-214b1ab4dfa4>", line 4, in <module>
assert age>0
AssertionError
当 assert 语句中的条件不满足时,我们还可以给出一条要打印的消息。用 assert 语句打印消息的语法是assert condition, message。message应该是字符串常量。每当 assert 语句中的condition计算为False时,程序将产生一个AssertionError,并打印message。
age= -10
print("Age is:")
print(age)
assert age>0 , "Age should be positive integer"
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
输出:
Age is:
-10
Traceback (most recent call last):
File "<ipython-input-10-82c11649bdd0>", line 4, in <module>
assert age>0 , "Age should be positive integer"
AssertionError: Age should be positive integer
在输出中,我们可以看到“年龄应该是正整数”的消息也和AssertionError一起打印出来。
如果想禁止程序过早退出,我们也可以使用 try except 块来处理AssertionError。可能有这样的情况,当 python 写入文件操作已经执行,如果程序过早退出,写入文件的数据将不会被保存。为了保存写入文件的数据,我们需要在程序退出前关闭文件。为此,我们必须使用 try except 块和 assert 语句,如下所示。
try:
age= -10
print("Age is:")
print(age)
assert age>0
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except AssertionError:
print("Input Correct age.")
输出:
Age is:
-10
Input Correct age.
在输出中,我们可以看到当 age 小于 0 时,AssertionError已经发生,但是已经被 except 块中的代码处理。如果我们想要执行任何文件操作,那么我们可以在 except 块中实现代码,或者我们可以使用 finally 块来实现代码。
为用户定义的异常定义自定义类
为了创建一个用户定义的异常,我们创建一个具有期望异常名称的类,它应该继承异常类。之后,我们可以根据实现约束的需要在代码中的任何地方引发异常。
为了生成一个用户定义的异常,我们在满足特定条件时使用“raise”关键字。然后由代码的 except 块处理该异常。然后我们使用 pass 语句。pass 语句用于表明我们不会在自定义异常类中实现任何东西。它被用作一个占位符,什么也不做,但我们仍然必须使用它,因为如果我们将自定义类的主体留空,python 解释器将显示我们的代码中有错误。
示例:
class NegativeAgeError(Exception):
pass
try:
age= -10
print("Age is:")
print(age)
if age<0:
raise NegativeAgeError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except NegativeAgeError:
print("Input Correct age.")
输出:
Age is:
-10
Input Correct age.
这里我们可以看到,当 age 的值小于零时,程序中的 try 块使用 raise 关键字抛出NegativeAgeError。然后由 except 块处理该异常。如果我们将年龄的正确值作为输入,它将正常打印出生年份。
class NegativeAgeError(Exception):
pass
try:
age= 10
print("Age is:")
print(age)
if age<=0:
raise NegativeAgeError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except NegativeAgeError:
print("Input Correct age.")
输出:
Age is:
10
Year of Birth is:
2011
结论:
在本文中,我们看到了如何使用自定义异常处理方法(如 assert 关键字、raise 关键字和自定义异常类)在 python 中实现对变量值的约束。我们也可以使用用户定义的异常在我们的程序中实现不同的现实约束,这样程序在语法上是正确的,逻辑上是合理的。敬请关注更多文章。
在 Python 中使用 Feedparser
原文:https://www.pythonforbeginners.com/feedparser/using-feedparser-in-python
概观
在本帖中,我们将看看如何使用 Python 下载和解析整合的
提要。
我们将使用的 Python 模块是“Feedparser”。
完整的文档可以在这里找到。
什么是 RSS?
RSS 代表 Rich Site Summary,使用标准的 web feed 格式发布经常更新的信息:博客条目、新闻标题、音频、视频。
一个 RSS 文档(称为“feed”、“web feed”或“channel”)包括完整或
摘要文本,以及元数据,如出版日期和作者姓名。来源
什么是 Feedparser?
Feedparser 是一个 Python 库,可以解析所有已知格式的提要,包括
Atom、RSS 和 RDF。它可以在 Python 2.4 一直运行到 3.3。来源
RSS 元素
在我们安装 feedparser 模块并开始编码之前,让我们看一看一些可用的 RSS 元素。
RSS 提要中最常用的元素是“标题”、“链接”、“描述”、“T0”、“发布日期”和“条目 ID”。
不太常用的元素是“图像”、“类别”、“附件”和“云”。
安装 Feedparser
要在你的电脑上安装 feedparser,打开你的终端,使用
" pip" (一个安装和管理 Python 包的工具)进行安装
sudo pip 安装 feedparser
要验证是否安装了 feedparser,可以运行一个“pip list”。
当然,您也可以进入交互模式,并在那里导入 feedparser
模块。
如果您看到如下输出,您可以确定它已经安装。
>>> import feedparser
>>>
既然我们已经安装了 feedparser 模块,我们就可以开始使用它了。
获取 RSS 源
你可以使用任何你想要的 RSS 源。因为我喜欢读 Reddit 的文章,所以我用 T2 的文章作为例子。
reddit 由许多子 Reddit 组成,我现在对
特别感兴趣的是“Python”子 Reddit。
获取 RSS 提要的方法是只需查找该子 reddit 的 URL 并
添加一个“rss”给它。
我们需要的 python 子 reddit 的 RSS 提要是:
http://www.reddit.com/r/python/.rss
使用 Feedparser
您从导入 feedparser 模块开始您的程序。
import feedparser
创建提要。放入你想要的 RSS 源。
d = feedparser.parse('http://www.reddit.com/r/python/.rss')
频道元素在 d.feed 中可用(还记得上面的“RSS 元素”吗)
这些项目在 d.entries 中可用,这是一个列表。
您访问列表中的项目的顺序与它们在
原始提要中出现的顺序相同,因此第一个项目在 d.entries[0]中可用。
打印源的标题
print d['feed']['title']
>>> Python
解析相对链接
print d['feed']['link']
>>> http://www.reddit.com/r/Python/
解析转义的 HTML
print d.feed.subtitle
>>> news about the dynamic, interpreted, interactive, object-oriented, extensible
programming language Python
查看条目数量
print len(d['entries'])
>>> 25
提要中的每个条目都是一个字典。使用[0]打印第一个条目。
print d['entries'][0]['title']
>>> Functional Python made easy with a new library: Funcy
打印第一个条目及其链接
print d.entries[0]['link']
>>> http://www.reddit.com/r/Python/comments/1oej74/functional_python_made_easy_with_a_new_
library/
使用 for 循环打印所有文章及其链接。
for post in d.entries:
print post.title + ": " + post.link + "
"
>>>
Functional Python made easy with a new library: Funcy: http://www.reddit.com/r/Python/
comments/1oej74/functional_python_made_easy_with_a_new_
library/
Python Packages Open Sourced: http://www.reddit.com/r/Python/comments/1od7nn/
python_packages_open_sourced/
PyEDA 0.15.0 Released: http://www.reddit.com/r/Python/comments/1oet5m/
pyeda_0150_released/
PyMongo 2.6.3 Released: http://www.reddit.com/r/Python/comments/1ocryg/
pymongo_263_released/
.....
.......
........
报告馈送类型和版本
print d.version
>>> rss20
对所有 HTTP 头的完全访问权限
print d.headers
>>>
{'content-length': '5393', 'content-encoding': 'gzip', 'vary': 'accept-encoding', 'server':
"'; DROP TABLE servertypes; --", 'connection': 'close', 'date': 'Mon, 14 Oct 2013 09:13:34
GMT', 'content-type': 'text/xml; charset=UTF-8'}
只需从头部获取内容类型
print d.headers.get('content-type')
>>> text/xml; charset=UTF-8
使用 feedparser 是解析 RSS 提要的一种简单而有趣的方式。
来源
http://www.slideshare.net/LindseySmith1/feedparser
http://code.google.com/p/feedparser/
在 python 中使用数学
原文:https://www.pythonforbeginners.com/basics/using-math-in-python
Python 中的数学
Python 发行版包括 Python 解释器,一个非常简单的开发
环境,称为 IDLE、库、工具和文档。
Python 预装在许多(如果不是全部)Linux 和 Mac 系统上,但它可能是旧版本。
计算器
要开始使用 python 解释器作为计算器,只需在
shell 中输入 Python。
>>> 2 + 2
4
>>> 4 * 2
8
>>> 10 / 2
5
>>> 10 - 2
8
用变量计数
在变量中输入一些值来计算矩形的面积
>>> length = 2.20
>>> width = 1.10
>>> area = length * width
>>> area
2.4200000000000004
计数器
计数器在编程中很有用,每次运行
时增加或减少一个值。
>>> i = 0
>>> i = i + 1
>>> i
1
>>> i = 1 + 2
>>> i
3
用 While 循环计数
这里有一个例子说明了使用计数器的用处
>>> i = 0
>>> while i < 5:
... print i
... i = i + 1
...
0
1
2
3
4
程序从 0 数到 4。在单词 while 和冒号之间,有一个
表达式,起初为真,但随后变为假。
只要表达式为真,下面的代码就会运行。
需要运行的代码必须缩进。
最后一条语句是一个计数器,每当循环
运行时,它的值就加 1。
乘法表
用 Python 制作乘法表很简单。
table = 8
start = 1
max = 10
print "-" * 20
print "The table of 8"
print "-" * 20
i = start
while i <= max:
result = i * table
print i, " * ", table, " =" , result
i = i + 1
print "-" * 20
print "Done counting..."
print "-" * 20
输出:
———————
8
的表—————
1 * 8 = 8
2 * 8 = 16
3 * 8 = 24
4 * 8 = 32
5 * 8 = 40
6 * 8 = 48
7 * 8 = 56
8 * 8 = 64
9 * 8 = 72
10 * 8 = 80
———
使用 Python 发送电子邮件
原文:https://www.pythonforbeginners.com/code-snippets-source-code/using-python-to-send-email
Python 在标准库中包含了几个模块,用于处理电子邮件和电子邮件服务器。
smtplib 概述
smtplib 模块定义了一个 SMTP 客户端会话对象,该对象可用于向任何带有 SMTP 或 ESMTP 侦听器守护程序的互联网计算机发送邮件。
SMTP 代表简单邮件传输协议。smtplib 模块对于与邮件服务器通信以发送邮件非常有用。
使用 SMTP 服务器通过 Python 的 smtplib 发送邮件。
实际使用情况取决于电子邮件的复杂性和电子邮件服务器的设置,此处的说明基于通过 Gmail 发送电子邮件。
smtplib 用法
这个例子取自 wikibooks.org 的这篇帖子
"""The first step is to create an SMTP object, each object is used for connection
with one server."""
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
#Next, log in to the server
server.login("youremailusername", "password")
#Send the mail
msg = "
Hello!" # The /n separates the message from the headers
server.sendmail("[email protected]", "[email protected]", msg)
要包含 From、To 和 Subject 标题,我们应该使用 email 包,因为 smtplib 根本不修改内容或标题。
电子邮件包概述
Python 的 email 包包含许多用于编写和解析电子邮件消息的类和函数。
电子邮件包使用
我们从只导入我们需要的类开始,这也使我们不必在以后使用完整的模块名。
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
然后,我们编写一些基本的消息头:
fromaddr = "[email protected]"
toaddr = "[email protected]"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "Python email"
接下来,我们将电子邮件正文附加到 MIME 消息中:
body = "Python test mail"
msg.attach(MIMEText(body, 'plain'))
为了发送邮件,我们必须将对象转换为字符串,然后使用与上面相同的程序通过 SMTP 服务器发送..
import smtplib
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login("youremailusername", "password")
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
验证电子邮件地址
SMTP 协议包含一个命令,用于询问服务器地址是否有效。通常 VRFY 是禁用的,以防止垃圾邮件发送者找到合法的电子邮件地址,但如果它被启用,您可以向服务器询问地址,并收到一个状态码,表明有效性以及用户的全名。
这个例子基于这个帖子
import smtplib
server = smtplib.SMTP('mail')
server.set_debuglevel(True) # show communication with the server
try:
dhellmann_result = server.verify('dhellmann')
notthere_result = server.verify('notthere')
finally:
server.quit()
print 'dhellmann:', dhellmann_result
print 'notthere :', notthere_result
使用 Gmail 发送邮件
这个例子取自http://rosettacode.org/wiki/Send_an_email#Python
import smtplib
def sendemail(from_addr, to_addr_list, cc_addr_list,
subject, message,
login, password,
smtpserver='smtp.gmail.com:587'):
header = 'From: %s
' % from_addr
header += 'To: %s
' % ','.join(to_addr_list)
header += 'Cc: %s
' % ','.join(cc_addr_list)
header += 'Subject: %s
' % subject
message = header + message
server = smtplib.SMTP(smtpserver)
server.starttls()
server.login(login,password)
problems = server.sendmail(from_addr, to_addr_list, message)
server.quit()
上述脚本的用法示例
sendemail(from_addr = '[[email protected]](/cdn-cgi/l/email-protection)',
to_addr_list = ['[[email protected]](/cdn-cgi/l/email-protection)'],
cc_addr_list = ['[[email protected]](/cdn-cgi/l/email-protection)'],
subject = 'Howdy',
message = 'Howdy from a python function',
login = 'pythonuser',
password = 'XXXXX')
收到的示例电子邮件
sendemail(from_addr = '[[email protected]](/cdn-cgi/l/email-protection)',
to_addr_list = ['[[email protected]](/cdn-cgi/l/email-protection)'],
cc_addr_list = ['[[email protected]](/cdn-cgi/l/email-protection)'],
subject = 'Howdy',
message = 'Howdy from a python function',
login = 'pythonuser',
password = 'XXXXX')
来源
[Python on Wikibooks.org](https://en.wikibooks.org/wiki/Python_Programming/Email "wikibooks_python")
[Rosettacode.org](https://rosettacode.org/wiki/Send_an_email#Python "rosettacode_python_email")
[Docs.python.org](https://docs.python.org/2/library/smtplib.html "python.org_smtplib")
[http://docs.python.org/2/library/email.mime.html](https://docs.python.org/2/library/email.mime.html "docs.python.org")
使用 pywhois 检索 whois 信息
原文:https://www.pythonforbeginners.com/python-on-the-web/using-pywhois
pywhois 是什么?
pywhois 是一个 Python 模块,用于检索域名的 whois 信息。pywhois 与 Python 2.4+一起工作,没有外部依赖【源】
装置
pywhois 的安装是通过 pip 命令完成的。
pip install python-whois
现在,当软件包安装完成后,您就可以开始使用它了。请记住,您必须首先导入它。
import whois
pywhois 用法
我们可以使用 pywhois 模块直接查询 whois 服务器,并解析给定域的 WHOIS 数据。我们能够提取所有流行顶级域名(com、org、net……)的数据
pywhois 示例
在 pywhois 项目网站上,我们可以看到如何使用 pywhois 提取数据。
让我们从导入 whois 模块开始,并创建一个变量。
>>> import whois >>> w = whois.whois('pythonforbeginners.com’)
要打印所有找到的属性的值,我们只需输入:
>>> print w
输出应该如下所示:
creation_date: [datetime.datetime(2012, 9, 15, 0, 0), '15 Sep 2012 20:41:00']
domain_name: ['PYTHONFORBEGINNERS.COM', 'pythonforbeginners.com']
...
...
updated_date: 2013-08-20 00:00:00
whois_server: whois.enom.com
我们可以打印出任何我们想要的属性。假设您只想打印出截止日期:
>>> w.expiration_date
显示从 whois 服务器下载的内容:
>>> w.text
为了使程序更具交互性,我们可以添加一个提示,用户可以在其中输入他们想要检索的 WHOIS 信息。
import whois
data = raw_input("Enter a domain: ")
w = whois.whois(data)
print w
在 pywhois 模块的帮助下,我们可以使用 Python 进行 whois 查找。
更多阅读
http://code.google.com/p/pywhois/
在 Python 中使用请求库
原文:https://www.pythonforbeginners.com/requests/using-requests-in-python
首先,让我们向您介绍请求。
什么是请求资源?
Requests 是一个 Apache2 许可的 HTTP 库,用 Python 编写。它被设计成供人类用来与语言互动。这意味着您不必手动向 URL 添加查询字符串,或者对您的帖子数据进行格式编码。如果这对你来说没有意义,不要担心。它会在适当的时候。
请求能做什么?
请求将允许您使用 Python 发送 HTTP/1.1 请求。有了它,您可以通过简单的 Python 库添加内容,如标题、表单数据、多部分文件和参数。它还允许您以同样的方式访问 Python 的响应数据。
在编程中,库是程序可以使用的例程、函数和操作的集合或预先配置的选择。这些元素通常被称为模块,并以对象格式存储。
库很重要,因为你加载一个模块并利用它提供的一切,而不用显式地链接到依赖它们的每个程序。它们是真正独立的,所以你可以用它们来构建你自己的程序,但它们仍然是独立于其他程序的。
把模块想象成一种代码模板。
重申一下,Requests 是一个 Python 库。
如何安装请求
好消息是有几种方法可以安装请求库。要查看可供您选择的选项的完整列表,您可以在此查看请求的官方安装文档。
您可以使用 pip、easy_install 或 tarball。
如果你更喜欢使用源代码,你也可以在 GitHub 上找到。
出于本指南的目的,我们将使用 pip 来安装库。
在 Python 解释器中,输入以下内容:
*pip install requests*
导入请求模块
要使用 Python 中的请求库,必须导入适当的模块。只需在脚本的开头添加以下代码,就可以做到这一点:
*import requests*
当然,要做到这些——包括安装库——您需要首先下载必要的包,并让解释器可以访问它。
提出请求
当您 ping 一个网站或门户网站以获取信息时,这被称为发出请求。这正是请求库的设计目的。
要获得一个网页,你需要做如下事情:
*r =* *requests.get**(‘https://github.com/**timeline.json**’)*
使用响应代码
在使用 Python 对网站或 URL 进行任何操作之前,最好检查一下所述门户的当前状态代码。您可以使用字典查找对象来实现这一点。
*r =* *requests.get**('https://github.com/**timeline.json**')*
*r.status**_code*
*>>200*
*r.status**_code* *==* *requests.codes.ok*
*>>> True*
*requests.codes**['**temporary_redirect**']*
*>>> 307*
*requests.codes**.teapot*
*>>> 418*
*requests.codes**['o/']*
*>>> 200*
获取内容
在 web 服务器返回响应后,您可以收集您需要的内容。这也是使用 get requests 函数完成的。
*import requests*
*r =* *requests.get**('https://github.com/**timeline.json**')*
*print* *r.text*
*#* *The* *Requests* *library* *also comes with a built**-**in JSON decoder,*
*#* *just* *in case* *you have to deal* *with JSON data*
*import requests*
*r =* *requests.get**('https://github.com/**timeline.json**')*
*print* *r.json*
使用标题
通过使用 Python 字典,您可以访问和查看服务器的响应头。由于 Requests 的工作方式,您可以使用任何大小写来访问标题。
如果您执行了这个函数,但是响应中不存在标题,那么这个值将默认为 None。
*r.headers*
*{*
* 'status': '200 OK',*
* 'content-encoding': '**gzip**',*
* 'transfer-encoding': 'chunked',*
* 'connection': 'close',*
* 'server': '**nginx**/1.0.4',*
* 'x-runtime': '148ms',*
* '**etag**': '"e1ca502697e5c9317743dc078f67693f"',*
* 'content-type': 'application/**json**; charset=utf-8'*
*}*
*r.headers**['Content-Type']*
*>>>'application/**json**; charset=utf-8'*
*r.headers.get**('content-type')*
*>>>'application/**json**; charset=utf-8'*
*r.headers**['X-Random']*
*>>>None*
*# Get the headers of a given URL*
*resp* *=* *requests.head**("http://www.google.com")*
*print* *resp.status**_code**,* *resp.text**,* *resp.headers*
编码
请求将自动十年从服务器拉任何内容。但是大多数 Unicode 字符集无论如何都是无缝解码的。
当您向服务器发出请求时,请求库会根据 HTTP 头对响应的编码进行有根据的猜测。当您访问 r.text 文件时,将使用猜测的编码。
通过这个文件,您可以辨别请求库使用的是什么编码,并在需要时进行更改。这是可能的,因为您将在文件中找到的 r.encoding 属性。
如果您更改编码值,只要您在代码中调用 r.text,请求就会使用新的类型。
*print* *r.encoding*
*>> utf-8*
*>>>* *r.encoding* *= ‘ISO-8859-1’*
自定义标题
如果要向请求添加自定义 HTTP 头,必须通过字典将它们传递给 headers 参数。
*import* *json*
*url* *= 'https://api.github.com/some/endpoint'*
*payload = {'some': 'data'}*
*headers = {'content-type': 'application/**json**'}*
*r =* *requests.post**(**url**, data=**json.dumps**(payload), headers=headers)*
重定向和历史记录
当您在 Python 中使用 GET 和 OPTIONS 谓词时,请求将自动执行位置重定向。
GitHub 会自动将所有 HTTP 请求重定向到 HTTPS。这保证了东西的安全和加密。
您可以使用 response 对象的 history 方法来跟踪重定向状态。
*r =* *requests.get**('http://github.com')*
*r.url*
*>>> 'https://github.com/'*
*r.status**_code*
*>>> 200*
*r.history*
*>>> []*
发出 HTTP Post 请求
您还可以使用请求库来处理 post 请求。
*r =* *requests.post**(http://httpbin.org/post)*
但是你也可以依赖其他 HTTP 请求,比如 PUT , DELETE , HEAD ,以及 OPTIONS 。
*r =* *requests.put**("http://httpbin.org/put")*
*r =* *requests.delete**("http://httpbin.org/delete")*
*r =* *requests.head**("http://httpbin.org/get")*
*r =* *requests.options**("http://httpbin.org/get")*
你可以用这些方法来完成很多事情。例如,使用 Python 脚本创建 GitHub repo。
*import requests,* *json*
*github_url* *= "https://api.github.com/user/repos"*
*data =* *json.dumps**({'**name':'test**', '**description':'some* *test repo'})*
*r =* *requests.post**(**github_url**, data,* *auth**=('user', '*****'))*
*print* *r.json*
错误和异常
在 Python 中使用请求库时,您需要熟悉许多异常和错误代码。
- 如果出现网络问题,如 DNS 故障或拒绝连接,请求库将引发 ConnectionError 异常。
- 对于无效的 HTTP 响应,请求也会引发 HTTPError 异常,但这种情况很少见。
- 如果请求超时,将引发超时异常。
- 如果请求超过预配置的最大重定向数,则会引发 TooManyRedirects 异常。
请求引发的任何异常都将从 Requests . exceptions . request exception 对象继承。
你可以通过下面的链接了解更多关于请求库的信息。
http://docs.python-requests.org/en/latest/api/
http://pipi . python . org/pipi/request】t1
http://docs.python-requests.org/en/latest/user/quickstart/
http://isbullsh.it/2012/06/Rest-api-in-python/#requests
在 Python 中使用 CSV 模块
原文:https://www.pythonforbeginners.com/csv/using-the-csv-module-in-python
如果要导入或导出电子表格和数据库以便在 Python 解释器中使用,则必须依赖 CSV 模块或逗号分隔值格式。
什么是 CSV 文件?
CSV 文件用于存储大量变量或数据。它们是极其简化的电子表格——想想 Excel——只是内容以明文形式存储。
CSV 模块是一个内置函数,允许 Python 解析这些类型的文件。
值得注意的是,当您处理 CSV 文件时,您正在涉足 JSON 开发。
JSON——代表 JavaScript 对象符号——是一种格式,用于在明文文件中以 JavaScript 代码的形式存储信息。您不需要了解 JavaScript 来处理这些文件,实践也不局限于该语言。显然,因为我们在这里使用的是 Python。
CSV 文件中的文本按行排列,每一行都有列,用逗号分隔。文件中的每一行都是电子表格中的一行,而逗号用于定义和分隔单元格。
使用 CSV 模块
要从 CSV 文件中提取信息,可以使用循环和分割方法从各个列中获取数据。
CSV 模块的存在就是为了处理这个任务,使得处理 CSV 格式的文件变得更加容易。当您处理从实际的电子表格和数据库导出到文本文件的数据时,这变得尤其重要。这些信息本身很难读懂。
不幸的是,没有标准,所以 CSV 模块使用“方言”来支持使用不同参数的解析。除了通用读取器和写入器,该模块还包括一种用于处理 Microsoft Excel 和相关文件的方言。
CSV 功能
CSV 模块包括所有内置的必要功能。它们是:
- csv .阅读器
- csv.writer
- csv.register_dialect
- csv.unregister_dialect
- csv.get_dialect
- csv.list _ 方言
- csv.field_size_limit
在本指南中,我们将只关注 reader 和 writer 函数,它们允许您编辑、修改和操作 CSV 文件中存储的数据。
读取 CSV 文件
要从 CSV 文件中提取数据,必须使用 reader 函数来生成 reader 对象。
reader 函数被设计成获取文件的每一行并列出所有列。然后,您只需选择需要可变数据的列。
听起来比实际复杂多了。为了证明这一点,我们来看一个例子。
*i**mport CSV*
*With* *open(**‘some.csv’, ‘**rb**’) as f:*
*r**eader =* *csv.reader**(f)*
*f**or row in reader:*
*p**rint row*
注意第一个命令是如何用于导入 CSV 模块的?
让我们看另一个例子。
*i**mport csv*
*i**mport sys*
*f* *= open(**sys.argv**[1], ‘**rb**’)*
*r**eader =* *csv.reader**(f)*
*f**or row in reader*
*p**rint row*
*f.close**()*
在前两行中,我们导入 CSV 和 sys 模块。然后,我们打开想要从中提取信息的 CSV 文件。
接下来,我们创建 reader 对象,迭代文件的行,然后打印它们。最后,我们结束操作。
CSV 样本文件
我们将看看一个示例 CSV 文件。注意信息是如何存储和呈现的。
*Title,Release* *Date,Director*
*And Now For Something Completely Different,**1971,Ian* *MacNaughton*
*Monty Python And The Holy Grail,**1975,Terry* *Gilliam and Terry Jones*
*Monty Python's Life Of Brian,**1979,Terry* *Jones*
*Monty Python Live At The Hollywood Bowl,**1982,Terry* *Hughes*
*Monty Python's The Meaning Of Life,**1983,Terry* *Jones*
读取 CSV 文件示例
我们将从一个基本的 CSV 文件开始,它有 3 列,包含变量“A”、“B”、“C”和“D”。
*$ cat test.csv*
*A,B**,”C D”*
*1,2,”3 4”*
*5,6,7*
然后,我们将使用下面的 Python 程序来读取和显示上述 CSV 文件的内容。
*import csv*
*ifile* *=* *open(**‘test.csv’, “**rb**”)*
*reader =* *csv.reader**(**ifile**)*
*rownum* *= 0*
*for row in reader:*
*# Save header row.*
*i**f* *rownum* *==0:*
*h**eader = row*
*e**lse:*
*c**olnum* *= 0*
*f**or col in row:*
*p**rint ‘%-8s: %s’ % (header[**colnum**], col)*
*c**olnum* *+ = 1*
*r**ownum* *+ = 1*
*i**file.close**()*
当我们用 Python 执行这个程序时,输出将如下所示:
*$ python csv1.py*
*A ** :* *1*
*B ** :* *2*
*C D ** :* *3 4*
*A ** :** 5*
*B ** :* *6*
*C D ** :* *7*
写入 CSV 文件
当您有一组想要存储在 CSV 文件中的数据时,是时候反过来使用 write 函数了。信不信由你,这和阅读它们一样容易做到。
writer() 函数将创建一个适合写的对象。要迭代行上的数据,需要使用writerow()**函数。
这里有一个例子。
以下 Python 程序将名为“test.csv”的文件转换为 csv 文件,该文件使用制表符作为值分隔符,所有值都用引号括起来。分隔符和引号,以及如何/何时引用,是在创建编写器时指定的。创建 reader 对象时,这些选项也是可用的。
*import csv*
*ifile** =* *open('test.csv', "**rb**")*
*reader =* *csv.reader**(**ifile**)*
*ofile** =* *open('ttest.csv', "**wb**")*
*writer =* *csv.writer**(**ofile**, delimiter='**',* *quotechar**='"', quoting=**csv.QUOTE_ALL**)*
*for row in reader:*
*writer.writerow**(row)*
*ifile.close**()*
*ofile.close**()*
当您执行这个程序时,输出将是:
*$ python csv2.py*
*$ cat ttest.csv*
*"A" "B" "C D"*
*"1" "2" "3 4"*
*"5" "6" "7"*
引用 CSV 文件
使用 CSV 模块,您还可以执行各种报价功能。
它们是:
- csv。引用_ 所有**–引用所有内容,不考虑类型。
- csv。引用_ 最小**–引用包含特殊字符的字段
- csv。引用_ 非数字**–引用所有非整数或浮点数的字段
- csv。引用_ 无**–不引用输出上的任何内容
更多 Python 阅读和资源
http://docs.python.org/2/library/csv.htmlhttp://www.doughellmann.com/PyMOTW/csv/http://effbot.org/librarybook/csv.htmhttp://www . Linux journal . com/content/handling-CSV-files-pythonhttp://programming-crash-course . code point . net/there _ are _ columns
在 Python 中使用 YouTube API
原文:https://www.pythonforbeginners.com/api/using-the-youtube-api
概观
在本帖中,我们将探讨如何在 Python 中使用 YouTube API。这个程序将展示我们如何使用 API 从 YouTube 中检索提要。这个特定的脚本将显示 YouTube 上目前最受欢迎的视频。
标准源
一些最受欢迎的 YouTube 源有:最近最受欢迎观看次数最多排名最高讨论次数最多最受欢迎链接次数最多特色最多回复次数
入门指南
为了从 YouTube 提要中获取我们想要的数据,我们首先要导入必要的模块。
import requests
import json
我们通过打印出程序所做的事情让它看起来更“漂亮”。然后,我们通过使用请求模块来获取提要。我以前使用 urllib2 模块来打开 URL,但是自从 Kenneth Reitz 给了我们请求模块之后,我就让这个模块来完成我的大部分 HTTP 任务。
r = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?v=2&alt=jsonc")
r.text
在我们获得提要并将其保存到变量“r”之后,我们将它转换成一个 Python 字典。
data = json.loads(r.text)
现在,我们有一个使用 for 循环来遍历数据
for item in data['data']['items']:
这有时可能是棘手的部分,你需要仔细观察这个结构是如何呈现给你的。使用一个 JSON 编辑器会使它变得更容易。
使用 YouTube API 获取数据
这个脚本将显示 YouTube 上最受欢迎的视频。
# Import the modules
import requests
import json
# Make it a bit prettier..
print "-" * 30
print "This will show the Most Popular Videos on YouTube"
print "-" * 30
# Get the feed
r = requests.get("http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?v=2&alt=jsonc")
r.text
# Convert it to a Python dictionary
data = json.loads(r.text)
# Loop through the result.
for item in data['data']['items']:
print "Video Title: %s" % (item['title'])
print "Video Category: %s" % (item['category'])
print "Video ID: %s" % (item['id'])
print "Video Rating: %f" % (item['rating'])
print "Embed URL: %s" % (item['player']['default'])
print
使用字符串格式使得查看代码更加容易。
# Sample Output ------------------------------ This will show the Most Popular Videos on YouTube ------------------------------ Video Title: PSY - GANGNAM STYLE (?????) M/V Video Category: Music Video ID: 9bZkp7q19f0 Video Rating: 4.614460 Embed URL: http://www.youtube.com/watch?v=9bZkp7q19f0&feature=youtube_gdata_player Video Title: PSY - GENTLEMAN M/V Video Category: Music Video ID: ASO_zypdnsQ Video Rating: 4.372500 Embed URL: http://www.youtube.com/watch?v=ASO_zypdnsQ&feature=youtube_gdata_player Video Title: MACKLEMORE & RYAN LEWIS - THRIFT SHOP FEAT. WANZ (OFFICIAL VIDEO) Video Category: Music Video ID: QK8mJJJvaes Video Rating: 4.857624 Embed URL: http://www.youtube.com/watch?v=QK8mJJJvaes&feature=youtube_gdata_player
如何使用其他 YouTube 源
要使用另一个 YouTube 标准提要,只需替换 URL 中的提要:http://gdata.youtube.com/feeds/api/standardfeeds/most _ responded?v=2 & alt=jsonc 您可能需要修改脚本来获得预期的结果。
ValueError:基数为 10 的 int()的文本无效
原文:https://www.pythonforbeginners.com/exceptions/valueerror-invalid-literal-for-int-with-base-10
Python 值错误:基数为 10 的 int()的无效文字是一个异常,当我们尝试使用 int()方法将字符串文字转换为整数,并且字符串文字包含除数字以外的字符时,可能会发生这种情况。在这篇文章中,我们将试图理解这种异常背后的原因,并将研究在我们的程序中避免它的不同方法。
Python 中的“ValueError:以 10 为基数的 int()的无效文字”是什么?
ValueError 是 python 中的一个异常,当将类型正确但值不正确的参数传递给方法或函数时,会出现该异常。消息的第一部分,即“value error”告诉我们,由于不正确的值作为参数传递给了 int()函数,因此出现了异常。消息的第二部分“基数为 10 的 int()的无效文字”告诉我们,我们试图将输入转换为整数,但输入中有十进制数字系统中的数字以外的字符。
int()函数的工作原理
python 中的 int()函数将一个字符串或一个数字作为第一个参数,并使用一个可选的参数基来表示数字格式。基数有一个默认值 10,用于十进制数,但是我们可以为基数传递一个不同的值,例如 2 表示二进制数,16 表示十六进制数。在本文中,我们将只使用带有第一个参数的 int()函数,base 的默认值将始终为零。这可以从下面的例子中看出。
我们可以将浮点数转换成整数,如下例所示。当我们使用 int()函数将一个浮点数转换成整数时,输出中的数字会去掉小数点后的数字。
print("Input Floating point number is")
myInput= 11.1
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input Floating point number is
11.1
Output Integer is:
11
我们可以将由数字组成的字符串转换为整数,如下例所示。这里的输入只包含数字,因此它将被直接转换成整数。
print("Input String is:")
myInput= "123"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
123
Output Integer is:
123
上面两个例子中显示的两种输入类型是 int()函数能够正常工作的唯一输入类型。对于其他类型的输入,当它们作为参数传递给 int()函数时,将生成 ValueError,并显示消息“对于以 10 为基数的 int()无效”。现在,我们将看看可以在 int()函数中为其生成 ValueError 的各种类型的输入。
什么时候出现“ValueError:以 10 为基数的 int()的无效文字”?
如上所述,当带有不适当值的输入被传递给 int()函数时,可能会出现基数为 10 的“value error:invalid literal for int()”。这可能发生在下列情况下。
1.Python 值错误:当 int()方法的输入是字母数字而不是数字时,基数为 10 的 int()的文字无效,因此输入无法转换为整数。这可以用下面的例子来理解。
在本例中,我们将一个包含字母数字字符的字符串传递给 int()函数,由于这个原因,会出现 ValueError,并在输出中显示消息“value error:invalid literal for int()with base 10”。
print("Input String is:")
myInput= "123a"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
123a
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-9-36c8868f7082>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '123a'
2.Python 值错误:当 int()函数的输入包含空格字符时,基数为 10 的 int()的文字无效,因此输入无法转换为整数。这可以用下面的例子来理解。
在本例中,我们将一个包含空格的字符串传递给 int()函数,由于这个原因,会出现 ValueError,并在输出中显示消息“value error:invalid literal for int()with base 10”。
print("Input String is:")
myInput= "12 3"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
12 3
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-10-d60c59d37000>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '12 3'
3.当 int()函数的输入包含任何标点符号(如句号“.”)时,就会出现 Python ValueError: invalid literal for int() with base 10或者逗号“,”。因此,输入不能转换成整数。这可以用下面的例子来理解。
在这个例子中,我们传递一个包含句点字符的字符串导致 ValueError 发生的 int()函数,并在输出中显示消息“ValueError:对于以 10 为基数的 int()无效的文本”。
print("Input String is:")
myInput= "12.3"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
输出:
Input String is:
12.3
Output Integer is:
Traceback (most recent call last):
File "<ipython-input-11-9146055d9086>", line 5, in <module>
myInt=int(myInput)
ValueError: invalid literal for int() with base 10: '12.3'
如何避免“ValueError:以 10 为基数的 int()的无效文字”?
我们可以避免 value error:invalid literal for int()with base 10 exception 使用先发制人的措施来检查传递给 int()函数的输入是否只包含数字。我们可以使用几种方法来检查传递给 int()的输入是否只包含数字,如下所示。
1.我们可以使用正则表达式来检查传递给 int()函数的输入是否只包含数字。如果输入包含数字以外的字符,我们可以提示用户输入不能转换为整数。否则,我们可以正常进行。
在下面给出的 python 代码中,我们定义了一个正则表达式“[^\d]”,它匹配十进制中除数字以外的所有字符。re.search()方法搜索模式,如果找到了模式,则返回一个 match 对象。否则 re.search()方法返回 None。
每当 re.search()返回 None 时,可以实现输入没有除数字之外的字符,因此输入可以被转换成如下的整数。
import re
print("Input String is:")
myInput= "123"
print(myInput)
matched=re.search("[^\d]",myInput)
if matched==None:
myInt=int(myInput)
print("Output Integer is:")
print(myInt)
else:
print("Input Cannot be converted into Integer.")
输出:
Input String is:
123
Output Integer is:
123
如果输入包含除数字以外的任何字符,re.search()将包含一个 match 对象,因此输出将显示一条消息,说明输入不能转换为整数。
import re
print("Input String is:")
myInput= "123a"
print(myInput)
matched=re.search("[^\d]",myInput)
if matched==None:
myInt=int(myInput)
print("Output Integer is:")
print(myInt)
else:
print("Input Cannot be converted into Integer.")
输出:
Input String is:
123a
Input Cannot be converted into Integer.
2.我们还可以使用 isdigit()方法来检查输入是否仅由数字组成。isdigit()方法接受一个字符串作为输入,如果作为参数传递给它的输入字符串只包含十进制的数字,则返回 True。否则,它返回 False。在检查输入字符串是否仅由数字组成后,我们可以将输入转换为整数。
在这个例子中,我们使用了 isdigit()方法来检查给定的输入字符串是否只包含数字。由于输入字符串“123”仅由数字组成,isdigit()函数将返回 True,并且使用 int()函数将输入转换为整数,如输出所示。
print("Input String is:")
myInput= "123"
print(myInput)
if myInput.isdigit():
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
else:
print("Input cannot be converted into integer.")
输出:
Input String is:
123
Output Integer is:
123
如果输入字符串包含除数字以外的任何其他字符,isdigit()函数将返回 False。因此,输入字符串不会被转换成整数。
在本例中,给定的输入是“123a ”,它包含一个字母表,因此 isdigit()函数将返回 False,并且在输出中将显示一条消息,说明输入不能转换为整数,如下所示。
print("Input String is:")
myInput= "123a"
print(myInput)
if myInput.isdigit():
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
else:
print("Input cannot be converted into integer.")
输出:
Input String is:
123a
Input cannot be converted into integer.
3.输入字符串可能包含一个浮点数并带有一个句点字符。在数字之间。要使用 int()函数将这样的输入转换为整数,首先我们将检查输入字符串是否包含浮点数,即在数字之间只有一个句点字符,或者没有使用正则表达式。如果是,我们将首先把输入转换成一个可以传递给 int()函数的浮点数,然后我们将显示输出。否则,它将被通知输入不能被转换成整数。
在这个例子中,“^\d+.\d$ "表示以一个或多个数字开始的模式,有一个句点符号。以一个或多个数字结尾,这是浮点数的模式。因此,如果输入字符串是浮点数,re.search()方法将不会返回 None,输入将使用 float()函数转换为浮点数,然后转换为整数,如下所示。
import re
print("Input String is:")
myInput= "1234.5"
print(myInput)
matched=re.search("^\d+\.\d+$",myInput)
if matched!=None:
myFloat=float(myInput)
myInt=int(myFloat)
print("Output Integer is:")
print(myInt)
else:
print("Input is not a floating point literal.")
输出:
Input String is:
1234.5
Output Integer is:
1234
如果输入不是浮点文字,re.search()方法将返回一个 None 对象,并在输出中显示输入不是浮点文字的消息,如下所示。
import re
print("Input String is:")
myInput= "1234a"
print(myInput)
matched=re.search("^\d+\.\d$",myInput)
if matched!=None:
myFloat=float(myInput)
myInt=int(myFloat)
print("Output Integer is:")
print(myInt)
else:
print("Input is not a floating point literal.")
输出:
Input String is:
1234a
Input is not a floating point literal.
对于使用正则表达式的两种方法,我们可以在使用 re.match()对象编写命名模式之后,使用 groupdict()方法编写一个单独的程序。groupdict()将返回输入中已命名的已捕获组的 python 字典,因此可用于识别可转换为整数的字符串。
4.我们还可以在 python 中使用异常处理,使用 python try except 在错误发生时处理 ValueError。在代码的 try 块中,我们通常会执行代码。每当 ValueError 发生时,它将在 try 块中引发,并由 except 块处理,并向用户显示一条正确的消息。
如果输入只包含数字并且格式正确,输出将如下所示。
print("Input String is:")
myInput= "123"
print(myInput)
try:
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
except ValueError:
print("Input cannot be converted into integer.")
输出:
Input String is:
123
Output Integer is:
123
如果输入包含除数字以外的字符,如字母或标点符号,将从 int()函数中抛出 ValueError,该函数将被 except 块捕获,并向用户显示一条消息,说明输入不能转换为整数。
print("Input String is:")
myInput= "123a"
print(myInput)
try:
print("Output Integer is:")
myInt=int(myInput)
print(myInt)
except ValueError:
print("Input cannot be converted into integer.")
输出:
Input String is:
123a
Output Integer is:
Input cannot be converted into integer.
结论
在本文中,我们看到了为什么“value error:invalid literal for int()with base 10”会出现在 python 中,并理解了其背后的原因和机制。我们还看到,通过首先检查 int()函数的输入是否仅由数字组成,或者不使用不同的方法(如正则表达式和内置函数),可以避免这种错误。
Python 中的变量和常量
原文:https://www.pythonforbeginners.com/basics/variables-and-constants-in-python
在学习 python 编程时,您一定遇到过某些短语,如关键字、变量、常量和文字。在本文中,我们将学习变量和常量,并研究它们在 python 中的定义和用法的基本概念。
Python 中有哪些变量?
python 中的变量是一个名称,用于引用内存中的对象。变量也称为引用,因为它们引用内存中的特定对象。
例如,以下代码片段中给出的变量myNum将引用一个 integer 类型的对象,该对象包含 1117 作为其值。
myNum = 1117
我们可以给变量赋值。同样,我们也可以将变量赋值给变量,如下所示。
myNum=1117
anotherNum=myNum
当我们给一个变量赋值时,两个变量都开始指向内存中的同一个对象。这可以使用 id()方法进行验证,该方法为每个对象提供一个惟一的标识符。
myNum = 1117
anotherNum = myNum
print("id of myNum is:", id(myNum))
print("id of anotherNum is:", id(anotherNum))
输出:
id of myNum is: 140209154920336
id of anotherNum is: 140209154920336
在上面的例子中,我们可以看到两个变量的 id 是相同的,这证实了两个变量引用了同一个对象。
我们也可以修改变量中的值。在修改可变数据类型的值时,新值被分配给同一个对象。例如,如果我们修改下面例子中给出的 python 字典中的一个键的值,字典将保持不变。这可以从修改前后的字典 id 来验证。
myDict = {1: 2}
print("Id of myDict before modification:", id(myDict))
myDict[1] = 4
print("Id of myDict after modification:", id(myDict))
输出:
Id of myDict before modification: 140457374471040
Id of myDict after modification: 140457374471040
当我们修改赋给不可变数据类型(如整数)的值时,会创建一个新对象并将其赋给变量。这可以从下面的例子中看出。
myNum=1117
print("Id of myNum before modification:", id(myNum))
myNum = 1118
print("Id of myNum after modification:", id(myNum))
输出:
Id of myNum before modification: 140485377224528
Id of myNum after modification: 140485378289104
在上面的例子中,我们可以看到 myNum 变量的 id 发生了变化。这确认了在给 myNum 赋值的过程中创建了一个新对象。
Python 中定义变量的约定
python 中的变量名总是以字母开头。我们可以用大写或小写字母开始一个变量,但是它不应该以数字或任何特殊字符开始。
name="PythonForBeginners" #correct variable name
Name="PythonForBeginners" #correct variable name
2name="PythonForBeginners" #incorrect variable name
#name="PythonForBeginners" #incorrect variable name
变量可以有下划线字符,但不能有任何其他特殊字符,如#、@、$、%、&、!。
my_name="PythonForBeginners" #correct variable name
my&name="PythonForBeginners" #incorrect variable name
当变量名由多个单词组成时,我们可以使用 camelCase 命名约定。在 camelCase 约定中,我们以一个小写字母开始变量,变量中的每个单词都以大写字母开始,如下所示。
myName="PythonForBeginners" #correct variable name
我们还可以使用下划线来分隔变量名中的不同单词,如下所示。
my_name="PythonForBeginners" #correct variable name
Python 是一种区分大小写的语言。这意味着拼写相同但大小写不同的变量名将引用不同的对象。
myNum=1117
MyNum = 1118
print("myNum is:",myNum)
print("MyNum is:",MyNum)
输出:
myNum is: 1117
MyNum is: 1118
在 python 中,关键字不应用作变量名,否则在程序执行过程中会出现错误。
in =1117 #incorrect variable name
Python 中的常量有哪些?
常量是文字,它包含一个在程序执行过程中不应该改变的值。
在 python 中,解释器不会区分变量和常量。在程序中,我们通过使用命名约定来区分变量和常量。
python 中的常量只使用大写字母和下划线定义。通常,常量是在一个模块中定义的,当我们需要使用它们的时候,它们就会被导入到程序中。例如,我们可以使用 cmath 模块中的常量 PI,在导入后如下所示。
import cmath
print("Value of PI is:",cmath.pi)
输出:
Value of PI is: 3.141592653589793
我们也可以在导入常量后修改它,如下所示。
import cmath
print("Value of PI is:", cmath.pi)
cmath.pi = 1117
print("modified value of PI is:", cmath.pi)
输出:
Value of PI is: 3.141592653589793
modified value of PI is: 1117
能够修改常量中的值完全违背了常量背后的思想。为了避免这种情况,应该在模块中定义 getter 函数来访问常量。这将限制用户修改这些值。
结论
在本文中,我们研究了 python 中的变量和常量。我们还看到了 python 中命名变量和常量的约定。我们还可以使用 python try except 编写本文中使用的程序,并使用异常处理来使程序更加健壮,并以系统的方式处理错误。请继续关注更多内容丰富的文章。
用 Python 创建字典的方法
原文:https://www.pythonforbeginners.com/dictionary/ways-to-create-dictionary-in-python
在 python 中,字典是一种数据结构,我们可以在其中以键值对的形式保存数据。在本文中,我们将研究和实现用 python 创建字典的各种方法。
用 python 创建一个空字典
我们可以使用花括号或字典构造函数创建一个空的 python 字典。
要使用花括号创建一个空字典,我们只需声明一个变量并分配一对花括号,如下所示。
myDict={}
print("Created dictionary is:")
print(myDict)
输出:
Created dictionary is:
{}
在上面的输出中,花括号显示已经创建了一个空字典。
要使用字典构造函数创建一个空字典,我们可以简单地调用构造函数dict()并将其赋给一个变量,如下所示。
myDict=dict()
print("Created dictionary is:")
print(myDict)
输出:
Created dictionary is:
{}
在上面的程序中,我们已经使用dict()构造函数创建了一个空字典。我们还可以使用上面的方法来创建已经定义了键值对的字典,这将在下面的章节中讨论。
用已经定义的键值对创建字典
要使用已经定义的键值对创建字典,我们可以使用花括号、字典构造函数或字典理解。
要使用花括号创建预定义键值对的字典,我们只需使用冒号编写键值对,并使用逗号分隔每个键值对,如下所示。
myDict={"name":"PythonForBeginners","acronym":"PFB"}
print("Created dictionary is:")
print(myDict)
输出:
Created dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
在上面的程序中,我们创建了一个字典,将name和acronym作为关键字,将PythonForBeginners和PFB分别作为字典中关键字的值。我们可以使用字典构造函数执行相同的操作。
在使用字典构造函数创建具有预定义键值对的字典时,我们将键和值作为关键字参数传递给 python 字典构造函数,如下所示。
myDict=dict(name="PythonForBeginners",acronym="PFB")
print("Created dictionary is:")
print(myDict)
输出:
Created dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
在输出中,我们可以看到我们已经创建了一个与前面方法相同的字典,但是使用了dict()构造函数来实现相同的目的。在程序中,键值对已作为关键字参数传递给构造函数,其中字典的键作为参数的关键字传递,字典的键的相应值作为值传递给关键字参数。
当给定包含键和值对的元组时,我们也可以创建字典。在这种情况下,元组索引 0 处的值成为字典的键,元组索引 1 处的值成为字典中相应键的值。
当我们在一个列表中有键-值对时,这个列表中的元组包含每个元组中的键和值,我们可以使用字典构造函数创建一个字典,如下所示。
myList=[("name","PythonForBeginners"),("acronym","PFB")]
myDict=dict(myList)
print("Created dictionary is:")
print(myDict)
输出:
Created dictionary is:
{'name': 'PythonForBeginners', 'acronym': 'PFB'}
在上面的程序中,我们可以验证字典的键是从元组中索引 0 处的元素创建的,并且各个键的值是从元组中索引 1 处的元素生成的。
可能会给我们一个键列表和一个单独的值列表来包含在字典中。为了创建字典,我们首先需要创建键值对元组,然后我们可以使用这些键值对创建字典。为了创建包含键和值对的元组,我们可以使用zip()函数。
zip()函数接受两个 iterable,并执行从第一个 iterable 的元素到第二个 iterable 的元素的一对一映射(基于索引)。如果在任何 iterable 中有额外的元素,它们将被忽略。
我们可以通过使用zip()函数和字典构造函数,使用给定的键和值列表创建一个 python 字典,如下所示。
keyList=["name","acronym"]
valueList=["Pythonforbeginners","PFB"]
temp=zip(keyList,valueList)
print("given list of keys is:")
print(keyList)
print("given list of values is:")
print(valueList)
print("Created key value pairs are:")
myList=list(temp)
print(myList)
myDict=dict(myList)
print("Created dictionary is:")
print(myDict)
输出:
given list of keys is:
['name', 'acronym']
given list of values is:
['Pythonforbeginners', 'PFB']
Created key value pairs are:
[('name', 'Pythonforbeginners'), ('acronym', 'PFB')]
Created dictionary is:
{'name': 'Pythonforbeginners', 'acronym': 'PFB'}
在上面的程序中,首先使用zip()函数生成一个包含键值对元组的列表,然后我们使用字典构造函数从元组列表中创建一个字典。
使用字典理解创建字典
正如我们使用 list comprehension 在 python 中创建列表一样,我们也可以使用 dictionary comprehension 在 python 中创建字典。通过从给定的 iterable 或 dictionary 为新字典创建键值对,我们可以从另一个字典或其他 iterable 创建字典。
假设我们想创建一个字典,其中包含一个列表中的元素作为键,它们的平方作为值,我们可以这样做。
myList=[1,2,3,4]
myDict={x:x**2 for x in myList}
print("List is:")
print(myList)
print("Created dictionary is:")
print(myDict)
输出:
List is:
[1, 2, 3, 4]
Created dictionary is:
{1: 1, 2: 4, 3: 9, 4: 16}
在输出中,我们可以看到创建的字典包含了作为键的列表元素和作为字典键的各自值的元素的平方。
我们还可以通过基于特定条件从另一个字典中选择键值对来创建一个新字典。对于这个任务,我们可以使用items()方法获得作为元组的键值对列表,然后我们可以根据任何给定的条件使用具有键值对的元组来创建新的字典。
假设我们想要创建一个新的字典,在这个字典中只选择原始字典中那些具有偶数作为键的键值对。这可以如下进行。
myDict={1:1,2:2,3:3,4:4}
print("Original Dictionary is")
print(myDict)
newDict={key:value**2 for (key,value) in myDict.items() if key%2==0}
print("New dictionary is:")
print(newDict)
输出:
Original Dictionary is
{1: 1, 2: 2, 3: 3, 4: 4}
New dictionary is:
{2: 4, 4: 16}
在上面的输出中,我们可以看到,我们已经从原始字典中有选择地为新字典选择了键值对,新字典只包含偶数的键。我们还通过平方修改了各自的值。
结论
在本文中,我们看到了用 python 创建字典的几种方法。我们已经看到了如何通过在 python 中实现不同的程序,使用花括号、字典构造器和字典理解来创建字典。请继续关注更多内容丰富的文章。
美声网刮
原文:https://www.pythonforbeginners.com/python-on-the-web/web-scraping-with-beautifulsoup
网页抓取
"网络抓取(网络采集或网络数据提取)是一种从网站提取信息的计算机软件技术."
在 Python 中 HTML 解析很容易,尤其是在 BeautifulSoup 库的帮助下。在这篇文章中,我们将抓取一个网站(我们自己的)来提取所有的 URL。
入门指南
首先,确保您已经安装了必要的模块。在下面的例子中,我们在安装了 Python 2.7 的系统上使用了 Beautiful Soup 4 和请求。使用 pip 可以安装 BeautifulSoup 和请求:
$ pip install requests
$ pip install beautifulsoup4
什么是美汤?
在他们网站的顶部,你可以读到:“你没有写那可怕的一页。你只是想从中获取一些数据。美丽的汤是来帮忙的。自 2004 年以来,它已经为程序员节省了数小时或数天的快速屏幕抓取项目工作。
美丽的汤特色:
Beautiful Soup 为导航、搜索和修改解析树提供了一些简单的方法和 Pythonic 式的习惯用法:一个用于解析文档和提取所需内容的工具包。编写应用程序不需要太多代码。
Beautiful Soup 自动将传入文档转换为 Unicode,将传出文档转换为 UTF-8。您不必考虑编码,除非文档没有指定编码,而且 Beautiful Soup 不能自动检测编码。然后,您只需指定原始编码。
Beautiful Soup 位于 lxml 和 html5lib 等流行的 Python 解析器之上,允许您尝试不同的解析策略或以速度换取灵活性。
从任何网站提取 URL
现在,当我们知道 BS4 是什么,并且我们已经在我们的机器上安装了它,让我们看看我们可以用它做什么。
from bs4 import BeautifulSoup
import requests
url = raw_input("Enter a website to extract the URL's from: ")
r = requests.get("http://" +url)
data = r.text
soup = BeautifulSoup(data)
for link in soup.find_all('a'):
print(link.get('href'))
当我们运行这个程序时,它会要求我们提供一个网站来提取网址
Enter a website to extract the URL's from: www.pythonforbeginners.com
> [通过实例学习 Python](https://www.pythonforbeginners.com/)
[https://www.pythonforbeginners.com/embed/#?secret=0SfA46x7bA](https://www.pythonforbeginners.com/embed/#?secret=0SfA46x7bA)
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/basics/python-lists-cheat-sheet/)
[https://www.pythonforbeginners.com/basics/python-lists-cheat-sheet/embed/#?secret=VYLwzbHO5d](https://www.pythonforbeginners.com/basics/python-lists-cheat-sheet/embed/#?secret=VYLwzbHO5d)
https://www.pythonforbeginners.com/loops/
https://www.pythonforbeginners.com/python-modules/
https://www.pythonforbeginners.com/strings/
https://www.pythonforbeginners.com/sitemap/
https://www.pythonforbeginners.com/feed/
> [通过实例学习 Python](https://www.pythonforbeginners.com/)
[https://www.pythonforbeginners.com/embed/#?secret=0SfA46x7bA](https://www.pythonforbeginners.com/embed/#?secret=0SfA46x7bA)
.... .... ....
推荐大家阅读我们的介绍文章:[美人汤 4 Python](https://www.pythonforbeginners.com/beautifulsoup/beautifulsoup-4-python) 获取更多关于美人汤的知识和了解。
##### 更多阅读
[http://www.crummy.com/software/BeautifulSoup/](http://www.crummy.com/software/BeautifulSoup/ "beautifulsoup")
[http://docs.python-requests.org/en/latest/index.html](http://docs.python-requests.org/en/latest/index.html "requests")
# 什么是好的评论/代码比?
> 原文:<https://www.pythonforbeginners.com/comments/what-is-a-good-comment-code-ratio>
注释是一段代码,当程序被执行时,它不会被编译器或解释器执行。只有当我们能够访问源代码时,才能阅读注释。要回答关于良好的注释/代码比率的问题,我们需要首先理解要求我们在源代码中包含注释的需求。
## 为什么需要评论?
众所周知,评论并不能提高节目的质量。它们提高了源代码的可读性和可理解性。下面是在我们的源代码中使用注释的一些具体原因。
### 1.我们使用注释来指定源代码的许可或版权。
当我们出于商业目的编写任何源代码时,通常会注明作者姓名、源代码创建的日期和时间。我们还指定源代码是否受版权保护或获得许可,以及是否可以在未经代码作者许可的情况下使用和修改源代码。
### 2.我们使用注释来指定合同(如果有的话)。
如果源代码是为了商业目的为不同的公司编写的,通常使用条件、版权都在源代码中指定。当任何人试图修改代码时,他们可以提前知道是否允许他们使用或修改源代码,以便将来不会出现法律问题。
以上两种用法都是通过在源代码中使用头注释来完成的。标题注释写在程序文件的开头,它们指定作者、创建日期、许可证,并描述文件中源代码的作用。如果任何人对源代码做了任何修改,也应该在头注释中监听,这样其他人就可以获得相关信息。
例如,下面的代码片段显示了一个 python 程序文件开头的 [python 注释](https://www.pythonforbeginners.com/comments/comments-in-python)。
```py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 6 14:13:03 2021
@author: aditya1117
This code is for pythonforbeginners.com
"""
3.我们使用注释来记录源代码。
当为任何编程语言编写任何新的框架或库时,它都包括源代码中使用的每种方法及其用例的规范。这样做是为了让框架的用户知道如何使用源代码中的函数和方法。它还指定了函数和方法的参数、期望的输入值和期望的输出,以便程序员可以很容易地使用代码。
对于源代码的文档,我们在每个函数上面使用注释。这些注释也称为函数头注释。例如,以下示例中的注释描述了在它之后定义的函数。
#This function is an example of nested function which defines another function and executes it when called.
def outer_function():
x=10
print("It is outer function which encloses a nested function")
def nested_function():
print("I am in nested function and I can access x from my enclosing function's scope. Printing x")
print(x)
nested_function()
4.我们使用注释来阐明为什么要在源代码中编写特定的语句。
当特定函数或表达式的用法在源代码中不明显时,我们使用注释来说明为什么要在那里编写函数或语句。它增加了代码的可读性和可理解性。
5.我们使用注释来指定有助于调试代码的指令。
如果出现任何错误,将来可能需要修改代码的任何部分。在这种情况下,执行源代码修正的程序员需要了解函数的属性。他们需要清楚地理解守则中的每一句话,以便能够即兴发挥。为了让程序员在这种情况下理解代码,只要有必要,就应该在源代码中添加注释。
以上两个用例是在内联注释的帮助下完成的。
源代码中的注释应该做什么?
1.解释为什么要写一个声明。
注释需要能够解释为什么在源代码中使用了一个语句。同样,注释应该解释为什么只在对读者来说不明显的时候才写语句。不应添加多余的注释。如果在没有适当需要的情况下使用注释,注释不但不会增加代码的可理解性,反而会降低代码的可读性。
例如,下面代码中的注释解释了正在创建一个任何人都可以从代码中识别的 python 字典。因此,评论是多余的。
#define a dictionary
myDict= {"Name":"PythonForBeginners", "code":"PFB"}
2.不应解释语句如何执行任何操作。
如果有人已经写了相当长时间的代码,并且是一个有经验的程序员,他们可以很容易地理解源代码中编写的语句是如何执行的。只有当他们弄不明白为什么要使用这个语句时,他们才能理解代码。因此,评论不应该试图解释任何语句是如何工作的。
3.指定关于程序文件的元数据。
文件头的注释应该指定作者、创建日期、许可证,并描述文件中源代码的作用。如果任何人在源代码中做了任何修改,也应该在头文件注释中指明,以便其他人可以获得相关信息。函数头的注释应该指定函数的签名、输入细节、功能和输出。
结论
阅读完细节后,现在我们可以解决关于注释/代码比率的最初问题了。要明白的是没有标准的码/评比。只要符合目的,我们可以使用任意数量的评论。但是应该记住的是我们不应该在代码中包含多余的注释,我们也不应该评论源代码中写的明显的东西。注释应该用于增强源代码的可理解性和可维护性,而不应该解释代码中的每一条语句。
JSON 是什么
JSON 是什么?
JSON (JavaScript Object Notation)是一种紧凑的、基于文本的计算机数据交换格式。json 的官方互联网媒体类型是 application/json,JSON 文件扩展名是。json
JSON 建立在两种结构之上:
名称/值对的集合
值的有序列表。
JSON 采用这些形式:对象、数组、值、字符串、数字
目标
名称/值对的无序集合。以{开头,以}结尾。每个名称后接:(冒号)名称/值对由,(逗号)分隔。
排列
值的有序集合。开始于[结束于]。值由(逗号)分隔。
价值
可以是双引号中的字符串、数字、true 或 false 或 null,也可以是对象或数组。
线
零个或多个 Unicode 字符的序列,用双引号括起来,使用反斜杠转义。
数字
整数、长整型、浮点型
以下示例显示了描述一个人的对象的 JSON 表示:
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
JSON 数据结构直接映射到 Python 数据类型,因此这是一个强大的工具,可以直接访问数据,而不必编写任何 XML 解析代码。JSON 曾经像字典一样加载到 Python 中。
Python 中的命名空间是什么?
原文:https://www.pythonforbeginners.com/basics/what-is-namespace-in-python
名称空间是一个非常棒的想法——让我们多做一些吧!名称空间是用于组织 python 程序中分配给对象的名称的结构。在本文中,我们将了解 python 中名称和命名空间的概念。
Python 中的名字是什么?
名称或标识符是我们在 python 中创建对象时赋予对象的名称。
这个名字就是我们在程序中使用的变量名。在 python 中,我们可以声明变量名并将它们分配给对象,如下所示。
myInt = 1117
myString = "PythonForBeginners"
这里,我们定义了两个名为 myInt 和 myString 的变量,它们分别指向一个整数和一个字符串对象。
什么是名称空间?
简而言之,名称空间是名称和名称所引用的对象的详细信息的集合。我们可以把名称空间看作是一个 python 字典,它把对象名称映射到对象。字典的键对应于名称,值对应于 python 中的对象。
在 python 中,有四种类型的命名空间,即内置命名空间、全局命名空间、局部命名空间和封闭命名空间。我们将在接下来的章节中研究它们。
Python 中的内置命名空间是什么?
内置命名空间包含内置函数和对象的名称。它是在启动 python 解释器时创建的,只要解释器运行就存在,当我们关闭解释器时就被销毁。它包含内置数据类型、异常和函数的名称,如 print()和 input()。我们可以访问内置名称空间中定义的所有名称,如下所示。
builtin_names = dir(__builtins__)
for name in builtin_names:
print(name)
输出:
ArithmeticError
AssertionError
AttributeError
BaseException
BlockingIOError
BrokenPipeError
BufferError
BytesWarning
ChildProcessError
ConnectionAbortedError
ConnectionError
ConnectionRefusedError
ConnectionResetError
DeprecationWarning
EOFError
Ellipsis
EnvironmentError
Exception
False
FileExistsError
FileNotFoundError
FloatingPointError
FutureWarning
GeneratorExit
IOError
ImportError
ImportWarning
IndentationError
IndexError
InterruptedError
IsADirectoryError
KeyError
KeyboardInterrupt
LookupError
MemoryError
ModuleNotFoundError
NameError
None
NotADirectoryError
NotImplemented
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
PermissionError
ProcessLookupError
RecursionError
ReferenceError
ResourceWarning
RuntimeError
RuntimeWarning
StopAsyncIteration
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TimeoutError
True
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
__build_class__
__debug__
__doc__
__import__
__loader__
__name__
__package__
__spec__
abs
all
any
ascii
bin
bool
breakpoint
bytearray
bytes
callable
chr
classmethod
compile
complex
copyright
credits
delattr
dict
dir
divmod
enumerate
eval
exec
exit
filter
float
format
frozenset
getattr
globals
hasattr
hash
help
hex
id
input
int
isinstance
issubclass
iter
len
license
list
locals
map
max
memoryview
min
next
object
oct
open
ord
pow
print
property
quit
range
repr
reversed
round
set
setattr
slice
sorted
staticmethod
str
sum
super
tuple
type
vars
zip
在上面的例子中,我们可以看到 python 3.8 的内置名称空间中定义了 152 个名称。
python 中的全局命名空间是什么?
全局命名空间是在程序或模块级别定义的。它包含模块或主程序中定义的对象的名称。程序启动时会创建一个全局名称空间,该名称空间会一直存在,直到程序被 python 解释器终止。从下面的例子可以理解全局名称空间的概念。
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
return temp
在上面的例子中,myNum1 和 myNum2 位于程序的全局名称空间中。
Python 中的本地命名空间是什么?
局部命名空间是为类、函数、循环或任何代码块定义的。代码块或函数中定义的名字是局部的。不能在定义变量名的代码块或函数之外访问变量名。本地命名空间在代码块或函数开始执行时创建,并在函数或代码块终止时终止。从下面的例子可以理解本地名称空间的概念。
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
return temp
这里,变量名 num1、num2 和 temp 是在函数 add 的本地名称空间中定义的。
什么是封闭名称空间?
正如我们所知,我们可以在另一个代码块或函数中定义一个代码块或函数,在任何函数中定义的函数或代码块都可以访问外部函数或代码块的名称空间。因此,外部命名空间被称为内部函数或代码块的命名空间的封闭命名空间。这将从下面的例子中变得更加清楚。
myNum1 = 10
myNum2 = 10
def add(num1, num2):
temp = num1 + num2
def print_sum():
print(temp)
return temp
在上面的示例中,add()函数的本地名称空间是 print_sum()函数的封闭名称空间,因为 print_sum()是在 add()函数中定义的。
结论
在本文中,我们讨论了 python 中的名称和命名空间。我们还看到了不同类型的名称空间及其功能。你可以在列表理解中阅读这篇文章。请继续关注更多内容丰富的文章。
Python 中何时使用注释与文档字符串
原文:https://www.pythonforbeginners.com/comments/when-to-use-comments-vs-docstrings-in-python
给你的程序添加注释将有助于其他程序员理解你的工作。没有注释,理解别人的代码可能会很困难。这就是为什么作为 Python 程序员,知道什么时候使用注释而不是文档字符串是很重要的。
知道何时使用注释以及如何使用注释可能会令人困惑。你知道文档字符串和字符串注释的区别吗?
在本教程中,我们将介绍用 Python 编写注释的最佳实践。我们还将向您展示如何使用 docstrings,并解释它们与普通注释的不同之处。希望我们能够揭开 Python 代码文档化过程的神秘面纱。
到本文结束时,您应该已经牢牢掌握了在 Python 中什么时候使用注释,什么时候使用文档字符串。
使用 Python 块注释
用 Python 做注释有多种方式。这对初学者来说可能有点困惑。理解块注释和字符串注释之间的区别会使情况变得更加清晰。
在 Python 中,大部分注释都是使用块注释编写的。块注释前面有一个 # 符号。Python 会在程序运行时忽略这些语句。使用块注释来提供简短的解释性注释。
示例 1:如何用 Python 编写块注释
# this is a Python block comment
也可以在 Python 语句的末尾写一个注释。这些注释被称为行内注释。内联注释非常适合解释不明显的代码。
示例 Python 中的行内注释
offset = width + 1 # compensate for the screen border
行内注释非常有用,但是最好少用。在这里,少即是多是一个很好的规则。
使用 Python 字符串注释
块注释只占一行。如果你需要一个跨越多行的注释,你需要使用更多的块注释。如果你有一个很长的注释,或者需要注释掉一段代码,你可以使用字符串注释。字符串注释是用引号写的。
示例 3:如何用 Python 编写字符串注释
"""
This is an example of a string comment.
String comments can be many lines long.
Python will ignore them when you run the program.
"""
有了字符串注释,你的注释长度没有限制。但是需要谨慎。如果将字符串注释放在错误的位置,可能会被误认为是文档字符串。
例如,函数后面的字符串注释将被解释为 docstring。由于这个原因,一些 Python 程序员根本不使用字符串注释。
用 Python 字符串注释有错吗?
一些程序员不赞成使用字符串作为 Python 注释。因为它们可能与 docstrings 混淆,一些 Python 程序员甚至认为最好完全避免它们。
但是官方的说法是使用字符串注释完全没问题。甚至 Python 的创造者 Guido Van Rossum 也认可了这种技术。
何时使用 Python 注释
使用注释为他人和自己留下关于代码的注释。注释有多种用途,但它们通常是为开发人员准备的。
与 docstrings 不同,注释不会被转换成文档。写评论没有规则,只有准则。如果你环顾四周,你会发现关于什么时候和什么时候不做评论有不同的观点。
一般来说,大多数程序员会告诉你,在下列情况下,注释是必要的:
- 当你需要解释复杂的算法时。
- 如果您想留下关于未完成代码的待办事项或注释。
- 如果你需要警告。
- 当您想要包含可选代码时。
以下是你在评论时要记住的一些小技巧:
- 尽可能保持评论简短。
- 永远尊重和帮助他人。
- 用评论来解释为什么做出决定。
- 使用注释来解释某事如何工作。
什么是 Python Docstring?
Docstrings 代表文档字符串,它们提供了一种记录 Python 程序的方法。使用 docstring,程序可以提供其他程序员可能想要使用的函数、类和模块的描述。
使用 docstrings,Python 开发人员可以简单解释函数或类的用途。没有这样的文档,学习新的 Python 模块将非常困难——如果不是不可能的话。
docstring 也可以用来生成 API(A应用 P 编程 I 接口)。API 用于通过网络发送数据。要使用 API,有必要查阅文档并了解它是如何工作的。Docstrings 允许程序将文档直接包含在代码中,从而使生成文档变得更加容易。
如何在 Python 中使用 Docstrings
既然我们已经在 Python 中区分了文档字符串和注释,那么让我们更仔细地看看文档字符串是如何工作的以及如何使用它们。
如何声明一个 docstring : 使用三重引号创建一个新的 docstring。因此,文档字符串可能会与字符串注释混淆。
如何访问文档字符串:可以使用 doc 属性读取文档字符串。
Docstring 应该是什么样子?
与注释不同,docstrings 有一些正式的要求。首先,每个 docstring 都以与其相关的函数或类的简短摘要开始。
总结应该清晰简洁。程序员立即掌握一个函数做什么是很重要的。然而,这有时说起来容易做起来难,但应该永远是目标。
可以在摘要下面的空行中提供进一步的文档。docstring 的细节应该作为函数和参数的快速参考。
记录 Python 函数
在用 Python 编写函数文档时,一定要包括函数参数的描述。此外,给出函数返回值的详细解释,如果有的话。
示例 4:如何用 Python 编写函数文档
def get_neighbors(some_list, index):
"""Returns the neighbors of a given index in a list.
Parameters:
some_list (list): Any basic list.
index (int): Position of an item in some_list.
Returns:
neighbors (list): A list of the elements beside the index in some_list.
"""
neighbors = []
if index - 1 >= 0:
neighbors.append(some_list[index-1])
if index < len(some_list):
neighbors.append(some_list[index+1])
return neighbors
some_list = [8,7,"car","banana",10]
print(get_neighbors(some_list, 2))
输出
[7, 'banana']
在 Python 中访问文档字符串
要在 Python 中访问 docstring,请使用 doc 属性。这是一个特殊的属性,将检索 Python 函数或类的 docstring。我们可以使用 doc 属性从命令行打印 docstring。
示例 5:使用 doc 属性访问文档字符串
print(get_neighbors.__doc__)
输出
Returns the neighbors of a given index in a list.
Parameters:
some_list (list): Any basic list.
index (int): Position of an item in some_list.
Returns:
neighbors (list): A list of the neighboring elements of the index in some_list.
用文档字符串记录 Python 类
在用 Python 编写类的文档时,包括类所代表的内容的摘要以及对类的属性和方法的解释是很重要的。
该类中的每个方法也需要一个 docstring。下面,你会发现一个博客文章类的例子。Python 文档字符串用于提供该类及其方法的详细描述。
示例 5:如何用 Python 编写类的文档
class BlogPost:
"""
A generic blog post model.
...
Attributes
----------
author: str
who wrote the blog post
title: str
the title of the blog post
content: str
the body content of the blog post
Methods
----------
description():
Prints the author, title, and content of the blog post
"""
def __init__(self, author, title, content):
"""Constructs all the necessary attributes of the blog post object.
Parameters
----------
author: str
who wrote the blog post
title: str
the title of the blog post
content: str
the body content of the blog post
"""
self.author = author
self.title = title
self.content = content
def description(self):
"""Prints the author, title, and content of the blog post.
Returns
-------
None
"""
print(f'{self.author}\n{self.title}\n{self.content}')
当谈到用于编写文档字符串的样式选择时,程序员会有所不同。稍加研究,你可以找到许多风格指南。选择如何格式化 docstring 将取决于许多因素,其中最不重要的可能是个人选择。记住你的文档是针对谁的。
摘要
知道在 Python 中什么时候使用注释,什么时候使用文档字符串,对于构建健壮、复杂的程序至关重要。学习如何以及何时发表评论不仅有助于你的合作,还能节省你的时间。
与字符串注释不同,文档字符串是供公众阅读的。它们提供了对如何使用函数、类和模块的深入了解。这使得其他程序员更容易学习如何在他们自己的项目中使用该模块。
快速回顾一下注释与文档字符串:
- 使用注释来解释代码是如何工作的。
- 注释对于为你的程序工作的人留下注释是很棒的。
- Docstrings 提供了关于函数、类和模块的文档。
- 使用 docstrings 来教其他开发者如何使用你的程序。
相关职位
- 如何使用 Python 读取文件函数打开文本文件?
- 使用 Python split ()拆分字符串。
何时使用 try/catch 而不是 if/else
原文:https://www.pythonforbeginners.com/control-flow-2/when-to-use-try-catch-instead-of-if-else
在编程时,我们必须处理施加在变量上的许多约束,以便程序能够以正确的方式执行。为了对变量施加约束,我们使用 if else 块和 try catch 块。在本文中,我们将看到这两种构造是如何工作的,并且我们将研究可以使用 if-else 块和可以使用 try-except 块的条件。
if-else 的工作原理
在 python 或任何其他编程语言中,If-else 块用于根据条件语句控制程序中语句的执行。如果 If 块中提到的条件为真,则执行 if 块中编写的语句。如果条件评估为 False,则执行程序的 else 块中编写的语句。
If-else 块主要用于根据我们预先知道的条件对程序进行流程控制。
例如,假设我们在程序中执行除法运算。在这种情况下,除数中的变量不能为零。如果除数变为零,程序将出错,并出现ZeroDivisionError。
def dividewithoutcondition(dividend,divisor):
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
#Execute the function
dividewithoutcondition(10,2)
dividewithoutcondition(10,0)
输出:
Dividend is: 10
Divisor is: 2
Quotient is: 5.0
Dividend is: 10
Divisor is: 0
Traceback (most recent call last):
File "<ipython-input-2-f6b48848354a>", line 1, in <module>
runfile('/home/aditya1117/untitled0.py', wdir='/home/aditya1117')
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/aditya1117/untitled0.py", line 22, in <module>
dividewithoutcondition(10,0)
File "/home/aditya1117/untitled0.py", line 6, in dividewithoutcondition
quotient=dividend/divisor
ZeroDivisionError: division by zero
在上面的实现中,我们可以看到,当给定 0 作为除数时,出现错误,程序突然结束。为了避免错误,使程序按预期执行,我们可以按以下方式使用 if- else 块。
def dividewithifelse(dividend,divisor):
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
if divisor==0:
print("Divisor cannot be Zero")
else:
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
#Execute the function
dividewithifelse(10,2)
dividewithifelse(10,0)
输出:
Dividend is: 10
Divisor is: 2
Quotient is: 5.0
Dividend is: 10
Divisor is: 0
Divisor cannot be Zero
在上面的程序中,我们首先检查除数是否为零。在第一种情况下,即除数不为零时,程序正常工作。在第二次除法运算中,当除数为零时,程序打印出除数不能为零,并正常退出,不像没有任何条件检查的程序那样会出错。因此,可以使用 else 块在程序中实现抢先检查,这样程序就不会出错。
试捕作业
Python try-catch 块主要用于 Python 中的错误或异常处理。每当在 try 块中执行语句时发生错误并引发异常,catch 块就会处理该异常。try 块中的语句正常执行,直到出现错误。一旦出现错误,控制就转到 catch 块,并在那里处理错误。一般来说,如果我们不知道程序执行过程中会出现什么错误或异常,我们会使用 try-except 块。
如果我们想用 try-catch 块实现除数不能为零的约束来实现同一个程序除数,我们可以这样做。在 python 中,try-catch 块被称为 try-except 块。
def dividewithtryexcept(dividend,divisor):
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
try:
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
except(ZeroDivisionError):
print("Divisor cannot be Zero")
输出:
Dividend is: 10
Divisor is: 2
Quotient is: 5.0
Dividend is: 10
Divisor is: 0
Divisor cannot be Zero
这里,产生的输出与使用 if-else 块实现函数时的输出完全相同。但是这两种结构的工作方式完全不同。if-else 块优先工作并阻止错误发生,而 try-except 块在错误发生后处理错误。因此,在 try-except 块中,系统的使用比 if-else 块多。
尝试捕捉优于 if-else 的优势
- Try-catch 块可用于处理系统生成的错误,以及通过手动引发异常来实现条件语句,而 if else 块只能实现条件语句,不能处理系统生成的错误。
- 单个 try 块可以检查任意多的条件,然后抛出错误,这些错误将由 catch 块处理。而在使用 if-else 块时,我们必须为每个条件显式实现 if 块。
- 如果 else 块给源代码带来了很多复杂性,但是 try except 块很简单,因此使用 try-catch 块可以确保源代码的可读性。
if-else 优于 try-catch
- If else 语句以先发制人的方式运行,并通过检查条件来防止错误发生,而 try-catch 块允许错误发生,因为控制返回到系统,然后系统将控制转移回 catch 块。这样,if else 块比 try-catch 语句更有效。
- If-else 块完全由应用程序处理,但是当使用 try-catch 从 try 块引发异常时,控制被转移到系统,然后系统再次将控制转移回应用程序,异常由 catch 块处理。由于这个原因,try-except 块在执行时比 if-else 块开销更大。
什么时候使用 if-else 块?
当程序员预先知道程序执行时可能出现的情况时,必须使用 If-else 块而不是 try-catch 块。在这种情况下,使用 if else 语句而不是 try-except 块将使程序更加高效。
什么时候使用 try-catch?
在许多情况下,程序员可能无法预测和检查所有的条件。这可能会导致程序执行出错。在这种情况下,为了处理未修复的错误,程序员应该使用 try-except 块,而不是 if-else 语句。
每当执行像 python 读取文件或写入文件这样的文件操作时,可能会发生文件不在文件系统中或者在写入文件时关闭文件之前发生错误的情况。如果发生这种情况,程序可能会出错,之前所做的工作可能会丢失。为了避免这些事情,除了在执行文件操作时必须使用块。
结论
记住以上几点,可以得出结论,如果我们正在编写一个源代码,其中我们已经知道每个约束和变量可以取的值,那么应该使用 if-else 语句来实现这些约束。当我们不知道程序执行过程中会遇到什么情况时,我们应该使用 try-except 或 try-catch 块。此外,我们应该尽量避免使用 try-catch 或 try-except 块进行流控制。只有 if-else 块应该用于流控制。此外,在执行文件处理操作时,我们必须使用 try-except 块。请继续关注更多内容丰富的文章。
为什么 try-except 错误处理在 Python 中很有用
原文:https://www.pythonforbeginners.com/error-handling/why-try-except-error-handling-is-useful-in-python
异常和错误是任何程序中都不希望发生的事件,它们可能导致程序执行过早终止。在 python 中,我们使用 try-except 错误处理来处理带有 python try except 和 finally 块的异常。在本文中,我们将通过不同的例子来研究在 python 中使用异常处理的一些原因。所以让我们开始吧!
我们可以处理程序员无法预测的错误
在现实世界的应用中,程序中使用的变量有许多用例及约束。程序员不可能每次都检查所有的约束,他们可能会遗漏一些情况,这可能会导致程序在执行时出错。在这些情况下,我们可以使用 try-except 错误处理来处理意外错误,并在需要时恢复程序。
例如,假设用户在执行过程中按下ctrl+c或del键来中断程序,那么程序会因为出现KeyBoardInterrupt错误而突然终止。我们可以如下使用 try-except 错误处理来处理错误,并在终止程序之前显示自定义消息,或者我们可以执行其他语句来将程序的状态保存在文件系统中。这样,如果用户不小心按下中断程序的键,我们可以避免程序写入文件的数据丢失。
try:
dividend=int(input())
divisor=int(input())
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
except (KeyboardInterrupt):
print("Operation has been cancelled by the user")
使用 try-except 错误处理,我们可以处理运行时异常
即使程序处理了所有的约束并且程序在语法上是正确的,在程序执行期间也可能会出现不依赖于程序中实现的逻辑的错误。例如,如果在一个 python 读文件操作中没有找到一个文件,程序可能会出错,并可能提前终止执行。在这种情况下,程序应该表现得更健壮,并以平稳的方式处理这种情况。这可以使用 python 中的 try-except 错误处理来完成。。其他运行时错误,如ZeroDivisionError、KeyError、NameError、IndexError等,也可以使用有效的除尝试错误处理来处理。
例如,下面的程序被编写为将一个数除以另一个数,但是当除数变为零时,它将导致ZeroDivisionError,并且程序将终止给出如下输出。
dividend=10
divisor=0
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
输出:
Dividend is: 10
Divisor is: 0
Traceback (most recent call last):
File "<ipython-input-17-f6b48848354a>", line 1, in <module>
runfile('/home/aditya1117/untitled0.py', wdir='/home/aditya1117')
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "/usr/lib/python3/dist-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/aditya1117/untitled0.py", line 9, in <module>
quotient=dividend/divisor
ZeroDivisionError: division by zero
我们可以通过在 try-except 块中包含除法运算来避免程序过早终止,这样当ZeroDivisionError发生时,它将自动由 except 块中的代码处理。这可以在下面的程序中看到。
dividend=10
divisor=0
print("Dividend is:",end=" ")
print(dividend)
print("Divisor is:",end=" ")
print(divisor)
try:
quotient=dividend/divisor
print("Quotient is:",end=" ")
print(quotient)
except (ZeroDivisionError):
print("Divisor Cannot be zero")
输出:
Dividend is: 10
Divisor is: 0
Divisor Cannot be zero
我们可以使用 try-except 错误处理将错误处理代码与业务逻辑分开。
通过使用 try-except 错误处理,我们可以轻松地将处理错误的代码与实现逻辑的代码分开。使用 try except 错误处理使代码更具可读性,因为业务逻辑和错误处理代码是完全分离的。
例如,假设我们想确定一个人的出生年份,我们必须勾选年龄不能为负。我们将使用如下 if-else 条件语句来实现这一点。
age= -10
print("Age is:")
print(age)
if age<0:
print("Input Correct age.")
else:
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
输出:
Age is:
-10
Input Correct age.
在上面的程序中,我们在同一个代码块中检查并处理年龄为负的情况。我们可以使用 try-except 错误处理将条件检查分成一个块,将错误处理分成另一个块,如下所示。
try:
age= -10
print("Age is:")
print(age)
if age<0:
raise ValueError
yearOfBirth= 2021-age
print("Year of Birth is:")
print(yearOfBirth)
except ValueError:
print("Input Correct age.")
输出:
Age is:
-10
Input Correct age.
在这里,我们可以看到我们已经检查了 try 块中年龄的非负数,当年龄为负数时ValueError被引发。ValueError然后由 except 块中的代码处理打印消息。因此,我们将条件检查和错误处理代码分离到不同的块中,这将提高源代码的可读性。
我们可以使用 try-except 错误处理在调用堆栈中向上传播错误。
在 python 中,如果一个函数被另一个函数调用,它可以将错误传播给调用函数,就像被调用函数返回任何值一样。这种机制可用于将错误传播到函数堆栈中的任意数量的函数,因此它使我们能够自由地在一个地方实现所有的异常处理代码,而不是在每个函数中实现它。我们可以在主函数本身中使用 try-except 错误处理来处理所有错误,并在被调用的函数中引发异常或错误。每当在任何被调用的函数中出现异常时,它将被传播到主函数,在主函数中应该用适当的错误处理代码来处理它。
例如,在下面的代码中,ValueError是在函数a()中引发的,但是处理ValueError的代码是在函数b()中编写的。当函数b()调用函数 a()时,a()将错误传播给函数b(),然后处理错误并打印消息。
def a():
print("PythonForBeginners in function a")
raise ValueError
def b():
try:
print("PythonForBeginners in function b")
a()
except Exception as e:
print("Caught error from called function in function b")
#call function b
b()
输出:
PythonForBeginners in function b
PythonForBeginners in function a
Caught error from called function in function b
在上面的过程中,每当任何函数中出现异常时,python 解释器都会向后搜索函数调用堆栈,以检查特定错误的错误处理代码是否已在任何调用函数中实现,以防错误未在函数本身中得到处理。如果当前函数在任何阶段都没有正确的错误处理代码,错误将传播到当前函数的调用函数,直到找到正确的错误处理代码或到达主函数。
结论
在本文中,我们通过不同的例子了解了如何在 python 中使用 try-except 错误处理来执行不同的任务。我们还简要了解了错误是如何在函数调用堆栈中传播的,以及它对于编写模块化源代码是如何有用的。请继续关注更多内容丰富的文章。


浙公网安备 33010602011771号