Python 中的字符串方法
最后更新于 2020 年 9 月 21 日
字符串类,即str
提供了许多有用的方法来操作字符串。具体来说,我们将讨论执行以下操作的方法。
- 在字符串中搜索子字符串。
- 测试字符串
- 格式化字符串
- 转换字符串。
回想一下前一章,方法是属于对象的函数。但是,与函数不同,方法总是使用以下符号在对象上调用。
object.method_name(arg1, arg2, arg3, ...., argN)
好了,我们开始吧。
测试字符串
str
类的以下方法测试字符串中的各种类型的字符。
方法 | 描述 |
---|---|
str.isalnum() |
如果字符串中的所有字符都是字母数字(包含数字或字母或两者的字符串),则返回True 。否则False 。 |
str.isalpha() |
如果字符串中的所有字符都是字母,则返回True 。否则False 。 |
str.isdigit() |
如果字符串中的所有字符都是数字,则返回True 。否则False 。 |
str.islower() |
如果字符串中的所有字符都是小写,则返回True 。否则False 。 |
str.isupper() |
如果字符串中的所有字符都是大写的,则返回True 。否则False 。 |
str.isspace() |
如果字符串中的所有字符都是空白字符,则返回True 。否则False 。 |
以下是一些例子:
isalnum()方法
>>>
>>> s = "A bite of python"
>>> s.isalnum()
False
>>>
>>> "123".isalnum()
True
>>> "abc".isalnum()
True
>>> "abc123".isalnum()
True
>>>
isalpha()方法
>>>
>>> "123".isalpha()
False
>>>
>>> "zyz".isalpha()
True
>>>
>>> "$$$$".isalpha()
False
>>>
>>> "abc233".isalpha()
False
>>>
isdigit()方法
>>>
>>>
>>> "name101".isdigit()
False
>>>
>>> "101".isdigit()
True
>>>
>>> "101 ".isdigit()
False
>>>
>>> "101.129".isdigit()
False
>>>
islower()和 isupper()方法
>>>
>>> s
'A bite of python'
>>>
>>> s.islower()
False
>>>
>>> "abc".islower()
True
>>>
>>> s.isupper()
False
>>>
>>>
>>> "ABC".isupper()
True
>>>
isspace()方法
>>>
>>> "\n\t".isspace()
True
>>>
>>> " \n\t".isspace()
True
>>>
>>> "@ \n\t".isspace()
False
>>> "123".isspace()
False
搜索和替换字符串
str
类有以下方法允许您搜索字符串中的子字符串。
方法 | 描述 |
---|---|
endswith(sub) |
如果字符串以子字符串sub 结尾,则返回True 。否则False 。 |
startswith(sub) |
如果字符串以子字符串sub 开头,则返回True 。否则False 。 |
find(sub) |
返回找到子字符串sub 的字符串的最低索引。如果未找到子字符串sub ,则返回-1 。 |
rfind(sub) |
返回找到子字符串sub 的字符串的最高索引。如果未找到子字符串sub ,则返回-1 。 |
count(sub) |
它返回在字符串中找到的子字符串sub 的出现次数。如果没有发现事件0 被返回。 |
replace(old, new) |
用new 替换old 子串后,返回一个新的字符串。请注意,它不会更改调用它的对象。 |
一些例子:
>>>
>>> s = "abc"
>>> s.endswith("bc")
True
>>>
>>> "python".startswith("py")
True
>>>
>>> "Learning Python".find("n")
4
>>>
>>> "Learning Python".rfind("n")
14
>>>
>>> "Learning Python".find("at")
-1
>>>
>>>
>>> "procrastination is the thief of time".count("ti")
3
>>>
>>>
>>>
>>> s1 = "Learning C" # old string
>>> id(s1)
49447664 # id of s1
>>>
>>> s2 = s.replace("C", "Python") # replace() creates a new string and assigns it to s2
>>> s2
'Learning Python'
>>>
>>> id(s1)
49447664 # notice that s1 object is not changed at all
>>>
>>>
转换字符串
以下方法通常用于返回字符串的修改版本。
方法 | 描述 |
---|---|
lower() |
将字符串的所有字符转换为小写后,返回字符串的新副本。 |
upper() |
将字符串的所有字符转换为大写后,返回字符串的新副本。 |
capitalize() |
仅将字符串中的第一个字母大写后,返回字符串的新副本。 |
title() |
将每个单词的第一个字母大写后,返回字符串的新副本。 |
swapcase() |
将小写字母转换为大写字母后返回新副本,反之亦然。 |
strip() |
移除所有前导和尾随空白字符后,返回字符串的新副本。 |
strip(chars) |
从字符串的开头和结尾删除chars 后,返回字符串的新副本。 |
请始终记住,这些方法会返回一个新字符串,并且不会以任何方式修改调用它们的对象。
以下是一些例子:
下()方法
>>>
>>> "abcDEF".lower()
'abcdef'
>>>
>>> "abc".lower()
'abc'
>>>
上限()方法
>>>
>>> "ABCdef".upper()
'ABCDEF'
>>>
>>> "ABC".upper()
'ABC'
>>>
大写()和 title()方法
>>>
>>> "a long string".capitalize()
'A long string'
>>>
>>>
>>> "a long string".title()
'A Long String'
>>>
>>>
swapcase()方法
>>>
>>> "ABCdef".swapcase()
'abcDEF'
>>>
>>> "def".swapcase()
'DEF'
>>>
条带()方法
>>>
>>> s1 = "\n\tName\tAge"
>>> print(s1)
Name Age
>>>
>>>
>>> s2 = s1.strip()
>>> s2
'Name\tAge'
>>> print(s2)
Name Age
>>>
>>>
>>> s = "--Name\tAge--"
>>>
>>> s.strip("-") # return a new copy of string after removing - characters from beginning and end of the string
'Name\tAge'
>>>
>>>
格式化方法
下表列出了str
类的一些格式化方法。
方法 | 描述 |
---|---|
center(width) |
在长度和宽度字段中居中后,返回字符串的新副本。 |
ljust(width) |
返回长度和宽度字段中向左对齐的字符串的新副本。 |
rjust(width) |
在长度和宽度字段中返回向右对齐的字符串的新副本。 |
center()方法
>>>
>>> "NAME".center(20)
' NAME '
>>>
>>>
ljust()方法
>>>
>>> "NAME".ljust(10)
'NAME '
>>> "NAME".ljust(4)
'NAME'
>>> "NAME".ljust(5)
'NAME '
>>>
rjust()方法
>>>
>>> "NAME".rjust(10)
' NAME'
>>>
>>> "NAME".rjust(4)
'NAME'
>>>
>>> "NAME".rjust(5)
' NAME'
>>>
>>>
Python 中的if-else
语句
原文:https://overiq.com/python-101/if-else-statements-in-python/
最后更新于 2020 年 9 月 21 日
到目前为止,我们编写的程序执行得非常有序。现实世界中的程序不是这样运行的。有时,我们只希望在满足特定条件时执行一组语句。为了处理这些情况,编程语言提供了一些称为控制语句的特殊语句。除了控制程序的流程,当某些条件为真时,我们还使用控制语句来循环或跳过语句。
控制语句有以下几种类型:
- 如果语句
- if-else 语句
- if-elif-else 语句
- while 循环
- for 循环
- break 语句
- 连续语句
在本课中,我们将讨论前三个控制语句。
如果语句
if 语句的语法如下:
语法:
if condition:
<indented statement 1>
<indented statement 2>
<non-indented statement>
语句的第一行即if condition:
被称为 if 子句,condition
是一个布尔表达式,其计算结果为True
或False
。在下一行中,我们有一组语句。一个块只是一个或多个语句的集合。当一个语句块后跟 if 子句时,它被称为 if 块。请注意,if 块中的每个语句在 if 关键字右侧缩进相同的量。许多语言,如 C、C++、Java、PHP,使用花括号({}
)来确定块的开始和结束,但是 Python 使用缩进。if 块中的每个语句都必须缩进相同数量的空格。否则,您会得到语法错误。Python 文档建议将块中的每个语句缩进 4 个空格。在本课程的所有课程中,我们都使用这一建议。
工作原理:
if 语句执行时,测试条件。如果条件为真,则执行 If 块中的所有语句。另一方面,如果条件为假,则跳过 if 块中的所有语句。
没有缩进的 if 子句后面的语句不属于 if 块。例如,<non-indented statement>
不是 if 块的一部分,因此,不管 if 子句中的条件是真还是假,它都会一直执行。
这里有一个例子:
蟒蛇 101/章节-09/if_statement.py
number = int(input("Enter a number: "))
if number > 10:
print("Number is greater than 10")
首次运行输出:
Enter a number: 100
Number is greater than 10
第二次运行输出:
Enter a number: 5
请注意,在条件失败时的第二次运行中,if 块中的语句被跳过。在这个例子中,if 块只包含一个语句,但是您可以有任意数量的语句,只要记住适当地缩进它们。
现在考虑以下代码:
python 101/章节-09/if_statement_block.py
number = int(input("Enter a number: "))
if number > 10:
print("statement 1")
print("statement 2")
print("statement 3")
print("Executes every time you run the program")
print("Program ends here")
首次运行输出:
Enter a number: 45
statement 1
statement 2
statement 3
Executes every time you run the program
Program ends here
第二次运行输出:
Enter a number: 4
Executes every time you run the program
Program ends here
在这个程序中需要注意的重要一点是,只有第 3、4 和 5 行的语句属于 if 块。因此,第 3、4 和 5 行中的语句只有在 if 条件为真时才会执行,而第 6 和 7 行中的语句无论如何都会执行。
当您在 Python shell 中键入控制语句时,它的响应有些不同。回想一下,要将一条语句拆分成多行,我们使用行延续运算符(\
)。控制语句不是这种情况,Python 解释器会在您按下 enter 键后立即自动将您置于多行模式。考虑以下示例:
>>>
>>> n = 100
>>> if n > 10:
...
请注意,在按回车键后跟 if 子句后,Shell 提示从>>>
变为...
。Python shell 显示...
对于多行语句,它只是意味着您开始的语句尚未完成。
要完成 if 语句,请向 if 块添加如下语句:
>>>
>>> n = 100
>>> if n > 10:
... print("n is greater than 10")
...
Python shell 不会自动缩进您的代码,您必须自己缩进。当您在块中键入完语句后,按两次回车键执行该语句,您将返回到正常的提示字符串。
>>>
>>> n = 100
>>> if n > 10:
... print("n is greater than 10")
...
n is greater than 10
>>>
如果条件为假,我们到目前为止编写的程序会突然结束,而不会向用户显示任何响应。大多数情况下,即使条件为假,我们也希望向用户显示响应。我们可以使用 if-else 语句轻松做到这一点
if-else 语句
if-else 语句在条件为真时执行一组语句,在条件为假时执行另一组语句。这样,if-else 语句允许我们遵循两个行动过程。if-else 语句的语法如下:
语法:
if condition:
# if block
statement 1
statement 2
and so on
else:
# else block
statement 3
statement 4
and so on:
工作原理:
当 if-else 语句执行时,如果条件被评估为True
,则测试条件,然后执行 if 块中的语句。但是,如果条件是False
,则执行 else 块中的语句。
这里有一个例子:
例 1 :计算圆的面积和周长的程序
蟒蛇 101/第-09 章/计算 _ 圆 _ 面积 _ 周长. py
radius = int(input("Enter radius: "))
if radius >= 0:
print("Circumference = ", 2 * 3.14 * radius)
print("Area = ", 3.14 * radius ** 2 )
else:
print("Please enter a positive number")
首次运行输出:
Enter radius: 4
Circumference = 25.12
Area = 50.24
第二次运行输出:
Enter radius: -12
Please enter a positive number
现在我们的程序向用户显示了一个适当的响应,即使条件是假的,这也是我们想要的。
在 if-else 语句中,始终确保 if 和 else 子句正确对齐。否则将会引发语法错误。例如:
python 101/章节-09/if _ and _ else _ not _ aligned . py
radius = int(input("Enter radius: "))
if radius >= 0:
print("Circumference = ", 2 * 3.14 * radius)
print("Area = ", 3.14 * radius ** 2 )
else:
print("Please enter a positive number")
尝试运行上面的程序,您会得到如下语法错误:
q@vm:~/python101/Chapter-09$ python3 if_and_else_not_aligned.py
File "if_and_else_not_aligned.py", line 6
else:
^
SyntaxError: invalid syntax
q@vm:~/python101/Chapter-06$
要解决该问题,请将 if 和 else 子句垂直对齐,如下所示:
radius = int(input("Enter radius: "))
if radius >= 0:
print("Circumference = ", 2 * 3.14 * radius)
print("Area = ", 3.14 * radius ** 2 )
else:
print("Please enter a positive number")
下面是另一个例子:
例 2 :检查用户输入的密码的程序
蟒蛇 101/第-09 章/秘密 _ 世界. py
password = input("Enter a password: ")
if password == "sshh":
print("Welcome to the Secret World")
else:
print("You are not allowed here")
首次运行输出:
Enter a password: sshh
Welcome to the Secret World
第二次运行输出:
Enter a password: ww
You are not allowed here
嵌套的 if 和 if-else 语句
我们还可以在另一个 if 或 if-else 语句中编写 if 或 if-else 语句。这可以通过一些例子更好地解释:
另一个 if 语句中的 if 语句。
例 1: 检查学生是否符合贷款条件的程序
python 101/章节-09/nested_if_statement.py
gre_score = int(input("Enter your GRE score: "))
per_grad = int(input("Enter percent secured in graduation: "))
if per_grad > 70:
# outer if block
if gre_score > 150:
# inner if block
print("Congratulations you are eligible for loan")
else:
print("Sorry, you are not eligible for loan")
这里我们在另一个 if 语句中写了一个 if 语句。内部 if 语句被称为嵌套 if 语句。在这种情况下,内部 if 语句属于外部 if 块,而内部 if 块只有一个打印"Congratulations you are eligible for loan"
的语句。
工作原理:
首先评估外中频条件,即per_grad > 70
,如果是True
,那么程序的控制进入外中频模块。在外如果块gre_score > 150
条件被测试。如果是True
,则"Congratulations you are eligible for loan"
被打印到控制台。如果是False
,则控制从 if-else 语句中出来,执行其后的语句,并且不打印任何内容。
另一方面,如果外部 if 条件被评估为False
,则跳过外部 if 块内部语句的执行,控制跳转到 else(第 9 行)块以执行其内部语句。
首次运行输出:
Enter your GRE score: 160
Enter percent secured in graduation: 75
Congratulations you are eligible for loan
第二次运行输出:
Enter your GRE score: 160
Enter percent secured in graduation: 60
Sorry, you are not eligible for loan
这个程序有一个小问题。再次运行程序,输入小于 T1 的 T0 和大于 T3 的 T2,如下所示:
输出:
Enter your GRE score: 140
Enter percent secured in graduation: 80
如您所见,程序不输出任何内容。这是因为我们的嵌套 if 语句没有 else 子句。在下一个示例中,我们将在嵌套的 if 语句中添加一个 else 子句。
例 2: 另一个 if 语句内部的 if-else 语句。
python 101/章节-09/nested _ if _ else _ statement . py
gre_score = int(input("Enter your GRE score: "))
per_grad = int(input("Enter percent secured in graduation: "))
if per_grad > 70:
if gre_score > 150:
print("Congratulations you are eligible for loan.")
else:
print("Your GRE score is no good enough. You should retake the exam.")
else:
print("Sorry, you are not eligible for loan.")
输出:
Enter your GRE score: 140
Enter percent secured in graduation: 80
Your GRE score is no good enough. You should retake the exam.
工作原理:
这个程序的工作原理和上面完全一样,唯一的区别是我们在这里添加了一个 else 子句,对应于嵌套的 if 语句。因此,如果你输入的 GRE 分数小于 150,程序会打印“你的 GRE 分数不够好。你应该重考。”而不是什么都不打印。
编写嵌套的 if 或 if-else 语句时,请始终记住正确缩进所有语句。否则你会得到一个语法错误。
else 子句中的 if-else 语句。
示例 3: 根据输入的分数确定学生成绩的程序。
蟒蛇 101/第-09 章/测试 _ 多重 _ 条件. py
score = int(input("Enter your marks: "))
if score >= 90:
print("Excellent ! Your grade is A")
else:
if score >= 80:
print("Great ! Your grade is B")
else:
if score >= 70:
print("Good ! Your grade is C")
else:
if score >= 60:
print("Your grade is D. You should work hard on you subjects.")
else:
print("You failed in the exam")
首次运行输出:
Enter your marks: 92
Excellent ! Your grade is A
第二次运行输出:
Enter your marks: 75
Good ! Your grade is C
第三次运行输出:
Enter your marks: 56
You failed in the exam
工作原理:
当程序控制进入 if-else 语句时,测试第 3 行的条件(score >= 90)
。如果条件为True
,控制台上会打印"Excellent ! Your grade is A"
。如果条件为假,控制跳转到第 5 行的 else 子句,然后测试条件score >= 80
(第 6 行)。如果是真的,那么"Great ! Your grade is B"
被打印到控制台。否则,程序控制跳转到第 8 行的 else 子句。同样,我们有一个带有嵌套 if-else 语句的 else 块。测试条件(score >= 70)
。如果为真,则"Good ! Your grade is C"
被打印到控制台。否则,控制再次跳到第 11 行的 else 块。最后,测试条件(score >= 60)
,如果是True
,则"Your grade is D. You should work hard on you subjects."
被打印到控制台。另一方面,如果为假,则将"You failed the exam"
打印到控制台。此时,控件从外部 if-else 语句中出来,执行其后的语句。
虽然嵌套的 if-else 语句允许我们测试多个条件,但是它们的读写相当复杂。我们可以使用 if-elif-else 语句使上面的程序更加易读和简单。
if-elif-else 语句
If-elif-else 语句是 if-else 语句的另一种变体,它允许我们轻松地测试多个条件,而不是编写嵌套的 if-else 语句。if-elif-else 语句的语法如下:
语法:
if condition_1:
# if block
statement
statement
more statement
elif condition_2:
# 1st elif block
statement
statement
more statement
elif condition_3:
# 2nd elif block
statement
statement
more statement
...
else
statement
statement
more statement
...
表示你,表示你可以根据需要写任意多的 elif 子句。
工作原理:
当 if-elif-else 语句执行时,首先测试condition_1
。如果条件为真,则执行 If 块中的语句。结构的其余部分中的条件和语句被跳过,控制从 if-elif-else 语句中出来,执行其后的语句。
如果condition_1
为假,程序控制跳转到下一个 elif 子句,并测试condition_2
。如果condition_2
为真,则执行第一个 elif 块中的语句。if-elif-else 结构的其余部分中的条件和语句被跳过,控制权从 if-elif-语句中出来,执行其后的语句。
这个过程一直重复,直到发现 elif 子句为真。如果没有发现 elif 子句为真,那么最后执行 else 块中的语句块。
让我们使用 if-elif-语句重写上面的程序。
蟒蛇 101/章节-09/if _ elif _ else _ statement . py
score = int(input("Enter your marks: "))
if score >= 90:
print("Excellent! Your grade is A")
elif score >= 80:
print("Great! Your grade is B")
elif score >= 70:
print("Good! Your grade is C")
elif score >= 60:
print("Your grade is D. You should work hard on you studies.")
else:
print("You failed in the exam")
首次运行输出:
Enter your marks: 78
Good ! Your grade is C
第二次运行输出:
Enter your marks: 91
Excellent! Your grade is A
第三次运行输出:
Enter your marks: 55
You failed in the exam
正如你所看到的,上面的程序很容易阅读和理解,不像它的嵌套等价物。
Python 中的循环
最后更新于 2020 年 9 月 21 日
循环允许我们多次执行某组语句。
考虑以下小问题:
假设我们要将字符串"Today is Sunday"
打印 100 次到控制台。实现这一点的一种方法是创建一个 Python 脚本并调用print()
函数 100 次,如下所示:
print("Today is Sunday") # 1st time
print("Today is Sunday") # 2nd time
...
...
print("Today is Sunday") # 100th time
正如你可能已经猜到的,这是一种非常低效的解决问题的方法。这个程序也不能很好地扩展。如果我们决定将"Today is Sunday"
打印 1000 次,那么我们将不得不将相同的语句多写 900 次。
我们可以使用 while 循环重写上述程序,如下所示:
i = 1
while i <= 100:
print("Today is Sunday")
i += 1
以后,如果我们决定打印"Today is Sunday"
1000 次,我们需要做的就是用 1000 替换 100,我们就完成了。
不要太担心 while 循环的语法,在下一节中,我们将深入讨论所有内容。
Python 提供了两种类型的循环:
- while 循环
- for 循环
while 循环
while 循环是一个有条件控制的循环,只要条件为真,它就会执行语句。while 循环的语法是:
while condition:
<indented statement 1>
<indented statement 2>
...
<indented statement n>
<non-indented statement 1>
<non-indented statement 2>
第一行称为 while 子句。就像 if 语句一样,condition 是一个布尔表达式,其计算结果为布尔True
或False
。缩进的语句组称为 while 块或循环体。通常需要缩进,它告诉 Python 块的开始和结束位置。
以下是它的工作原理:
首先评估条件。如果条件为真,则执行 while 块中的语句。在 while 块中执行语句后,再次检查条件,如果条件仍然为真,则再次执行 while 块中的语句。while 块中的语句将继续执行,直到条件为真。循环体的每次执行都被称为迭代。当条件变为假时,循环终止,程序控制从 while 循环中出来,开始执行后面的语句。
现在我们知道 while 循环是如何工作的了。让我们好好看看我们用来打印"Today is Sunday"
到控制台的程序。
蟒蛇 101/第 10 章/a_while_loop.py
i = 1
while i <= 100:
print("Today is Sunday")
i += 1
在第 1 行,我们为变量i
赋值1
。当控制进入 while 循环时,测试 while 条件i <= 100
。如果为真,则执行 while 块中的语句。while 块中的第一个语句向控制台打印“今天是星期天”。第二条语句增加变量i
的值。在 while 块中执行语句后,将再次测试该条件。如果仍然被发现为真,那么 while 块中的语句将被再次执行。这个过程一直重复,直到i
小于或等于100
。当i
变为101
时,while 循环终止,程序控制从 while 循环中出来,执行后面的语句。
示例 2: 下面的程序使用 while 循环来计算从 0 到 10 的数字总和
蟒蛇 101/第 10 章/sum_from_0_to_10.py
i = 1
sum = 0
while i < 11:
sum += i # same as sum = sum + i
i += 1
print("sum is", sum) # print the sum
输出:
sum is 55
这个 while 循环一直执行到i < 11
。变量sum
用于累加从0
到10
的数字总和。在每次迭代中,值i
被添加到变量sum
中,i
增加1
。当i
变为11
时,循环终止,程序控制从 while 循环中出来,执行第 7 行的print()
功能。
在 while 循环的主体中,您应该包含一个改变条件值的语句,这样条件最终会在某个时候变为假。如果你不这样做,那么你会遇到一个无限循环——一个永不终止的循环。
假设我们错误地将上述程序编写为:
蟒蛇 101/第 10 章/无限循环
i = 1
sum = 0
while i < 11:
print(i)
sum += i
i += 1
print("sum is", sum)
这里的语句i += 1
在循环体之外,这意味着i
的值永远不会增加。因此,循环是无限的,因为条件i < 11
永远是真的。试着执行上面的程序,你会发现它会无限期地保持打印i
的值。
输出:
1
1
1
1
1
...
当系统内存不足时,无限循环通常会结束。要手动停止无限循环,请按 Ctrl + C。
然而,这并不意味着无限循环没有用。有一些编程任务,无限循环真的很出色。考虑以下示例:
例 3 :从华氏到摄氏计算温度的程序。
蟒蛇 101/章节-10/华氏 _ 至 _ 摄氏. py
keep_calculating = 'y'
while keep_calculating == 'y':
fah = int(input("Enter temperature in Fahrenheit: "))
cel = (fah - 32) * 5/9
print(format(fah, "0.2f"), "°F is same as", format(cel, "0.2f"), "°C")
keep_calculating = input("\nWant to calculate more: ? Press y for Yes, n for N: ")
print("Program Ends")
当你运行程序时,它会要求你输入华氏温度。然后,它将华氏温度转换为摄氏温度,并显示结果。此时,程序会问你"Want to calculate more: ?"
。如果输入y
,会再次提示输入华氏温度。然而,如果您按下n
或任何其他字符,循环终止,程序控制从 while 循环中出来并打印"Program Ends"
到控制台。
输出:
Enter temperature in Fahrenheit: 43
43.00 °F is same as 6.11 °C
Want to calculate more: ? Press y for Yes, n for N: y
Enter temperature in Fahrenheit: 54
54.00 °F is same as 12.22 °C
Want to calculate more: ? Press y for Yes, n for N: n
Program Ends
for 循环
在 Python 中,我们使用 for 循环遍历序列。
那么什么是序列呢?
序列是一个通用术语,指以下类型的数据:
- 线
- 目录
- 元组
- 词典
- 设置
注:这里我们只介绍了字符串,其余的类型后面会讨论。
for 循环的语法如下:
for i in sequence:
# loop body
<indented statement 1>
<indented statement 2>
...
<indented statement n>
语法中的第一行即for i in sequence:
被称为 for 子句。在下一行中,我们有缩进的语句块,它在每次循环迭代时执行。
假设序列是一个列表[11, 44, 77, 33, 199]
,那么遍历列表的代码可以写成:
for i in [11, 44, 77, 33, 199]:
# loop body
<indented statement 1>
<indented statement 2>
...
<indented statement n>
注:在 Python 中,方括号[]
内逗号分隔的值列表称为列表。我们将在第课详细讨论 Python 中的列表。
以下是它的工作原理:
在第一次迭代中,列表中的值11
被分配给变量i
,然后执行循环体内部的语句。这就完成了循环的第一次迭代。在第二次迭代中,列表中的下一个值,即44
被分配给变量i
,然后再次执行循环体中的语句。对下一个值重复相同的过程。当列表中的最后一个值199
被分配给变量i
并执行循环体时,循环终止。然后程序控制从循环中出来,开始执行跟随它的语句。
以下是一些例子:
示例 1 :用于遍历列表中元素的循环
>>>
>>> for i in [11, 44, 77, 33, 199]:
... print(i)
...
11
44
77
33
199
>>>
示例 2 :用于循环遍历字符串中的字符
>>>
>>> for i in "astro":
... print(i)
...
a
s
t
r
o
>>>
对于带 range()函数的循环
除了迭代序列,我们还使用 for 循环,当我们事先知道循环体需要执行多少次时。这种循环被称为计数控制循环。Python 提供了一个名为range()
的函数,它简化了创建计数控制循环的过程。range()
函数返回一个被称为可迭代的特殊类型的对象。就像序列一样,当我们迭代一个可迭代对象时,它会从一个期望的序列中返回一个连续的项。你可以把可迭代对象想象成列表,但它不是一个真实的列表。
最简单地说,range()
函数的语法是:
range(a)
其中a
是一个整数。
range(a)
返回从0
到a-1
的整数序列。
下面是创建一个 for 循环的代码,它执行循环体 5 次:
>>>
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>>
在上面的代码中,range(5)
返回一个从0
到4
的数字序列。在第一次迭代中range(5)
函数返回0
,然后将其分配给变量i
。然后执行循环体。在第二次迭代中range(5)
返回1
,然后将其分配给变量i
。循环体被再次执行。当4
被分配给变量i
并执行循环体时,循环终止。
上述代码相当于:
>>>
>>> for i in [0, 1, 2, 3, 4]:
... print(i)
...
0
1
2
3
4
>>>
range()
功能还有以下两个版本:
range(a, b)
range(a, b, c)
范围(a,b)
range(a, b)
返回一系列的形式为a
、a+1
、a+2
,…b-2
、b-1
。
例如:range(90, 100)
返回一个序列,一个从90
到99
的数字序列。
范围(a、b、c)
默认情况下,range()
函数返回一个数字序列,其中每个连续的数字都比它的前身大1
。如果你想改变这一点,把第三个参数传递给range()
函数。第三个参数称为步长值。例如:
range(0, 50, 5)
返回以下数字序列:
0, 5, 10, 15, 20, 25, 30, 35, 40, 45
请注意,每个数字之间用5
隔开。
以下是一些例子:
例 1:
>>>
>>> for i in range(10, 20):
... print(i)
...
10
11
12
13
14
15
16
17
18
19
>>>
例 2:
>>>
>>> for i in range(10, 20, 3): # step value is 3
... print(i)
...
10
13
16
19
>>>
我们还可以指定负步长值:
>>>
>>> for i in range(50, 0, -5):
... print(i)
...
50
45
40
35
30
25
20
15
10
5
>>>
以下程序使用 for 循环生成从1
到20
的数字的平方:
蟒蛇 101/第 10 章/方块 _ 从 _ 1 _ 到 _20.py
print("Number\t | Square")
print("--------------------")
for num in range(1, 21):
print(num, "\t\t | ", num*num)
输出:
Number | Square
--------------------
1 | 1
2 | 4
3 | 9
4 | 16
5 | 25
6 | 36
7 | 49
8 | 64
...
17 | 289
18 | 324
19 | 361
Python 中的break
和continue
语句
原文:https://overiq.com/python-101/break-and-continue-statement-in-python/
最后更新于 2020 年 9 月 21 日
break 语句
break
语句用于在满足特定条件时提前终止循环。当在循环体内部遇到break
语句时,当前迭代停止,程序控制立即跳转到循环后的语句。break
的说法可以写成如下:
break
以下示例演示了 break 语句的作用。
例 1:
蟒蛇 101/第 11 章/break_demo.py
for i in range(1, 10):
if i == 5: # when i is 5 exit the loop
break
print("i =", i)
print("break out")
输出:
i = 1
i = 2
i = 3
i = 4
break out
一旦i
的值为5
,条件i == 5
变为真,break
语句导致循环终止,程序控制跳转到 for 循环之后的语句。执行第 6 行的 print 语句,程序结束。
例 2:
以下程序提示用户输入一个数字,并确定输入的数字是否为质数。
蟒蛇 101/第 11 章/prime_or_not.py
num = int(input("Enter a number: "))
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False # number is not prime
break # exit from for loop
if is_prime:
print(num, "is prime")
else:
print(num, "is not a prime")
首次运行输出:
Enter a number: 11
11 is prime
第二次运行输出:
Enter a number: 23
23 is prime
第三次运行输出:
Enter a number: 6
6 is not a prime
质数是只能被1
或自身整除的数。以下是质数的一些例子:
1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 33, 37, 41
如果一个数n
不能被从2
到n-1
的任何数整除,那么它就是质数。请考虑以下示例:
例 1:
5 是素数吗?
以下是判断数字 5 是否是质数的步骤。
问题 | 编程语句 | 结果 |
---|---|---|
5 能被 2 整除吗? | 5 % 2 == 0 |
False |
5 能被 3 整除吗? | 5 % 3 == 0 |
False |
5 能被 4 整除吗? | 5 % 4 == 0 |
False |
结果:5 是质数
例 2:
9 是素数吗?
以下是判断数字 9 是否是质数的步骤。
问题 | 编程语句 | 结果 |
---|---|---|
9 能被 2 整除吗? | 9 % 2 == 0 |
False |
9 能被 3 整除吗? | 9 % 3 == 0 |
True |
第二步我们的测试9 % 3 == 0
通过了。换句话说,9
可以被3
整除,也就是说9
不是素数。在这一点上,用剩余的数字来检验9
的可分性是没有意义的。所以我们停下来。
这正是我们在上述程序中所做的。在第 1 行,我们要求用户输入一个数字。在第 3 行,我们已经用布尔值True
声明了一个变量is_prime
。最后,这个变量将决定用户输入的数字是否是质数。
for 循环迭代通过2
到num-1
。如果num
可以被该范围内的任意数字整除(第 6 行),我们将is_prime
设置为False
,并立即退出 for 循环。但是,如果条件n % i == 0
永远不满足break
语句将不会执行,is_prime
将保持设置为True
。在这种情况下num
将是一个质数。
嵌套循环中的 break 语句
在嵌套循环中,break
语句只终止它出现的循环。例如:
蟒蛇 101/第 11 章/break _ inside _ nested _ loop . py
for i in range(1, 5):
print("Outer loop i = ", i, end="\n\n")
for j in range (65, 75):
print("\tInner loop chr(j) =", chr(j))
if chr(j) == 'C':
print("\tbreaking out of inner for loop ...\n")
break
print('-------------------------------------------------')
输出:
Outer loop i = 1
Inner loop chr(j) = A
Inner loop chr(j) = B
Inner loop chr(j) = C
breaking out of inner for loop ...
-------------------------------------------------
Outer loop i = 2
Inner loop chr(j) = A
Inner loop chr(j) = B
Inner loop chr(j) = C
breaking out of inner for loop ...
-------------------------------------------------
Outer loop i = 3
Inner loop chr(j) = A
Inner loop chr(j) = B
Inner loop chr(j) = C
breaking out of inner for loop ...
-------------------------------------------------
Outer loop i = 4
Inner loop chr(j) = A
Inner loop chr(j) = B
Inner loop chr(j) = C
breaking out of inner for loop ...
-------------------------------------------------
对于外部循环的每次迭代,内部 For 循环执行三次。一旦条件chr(j) == 'C'
满足break
语句,就会立即退出内部 for 循环。然而,外部 for 循环将照常执行。
连续语句
continue
语句用于前进到下一个迭代,而不执行循环体中的剩余语句。就像break
语句一样,continue
语句一般与条件连用。continue
语句可以写成如下:
continue
这里有一个例子来演示continue
语句的工作原理:
蟒蛇 101/第 11 章/continue_demo.py
for i in range(1, 10):
if i % 2 != 0:
continue
print("i =", i)
输出:
i = 2
i = 4
i = 6
i = 8
在上述程序中,当条件i % 2 != 0
评估为True
时,执行continue
语句,省略循环体内print()
函数的执行,程序控制前进到循环的下一次迭代。
我们也可以在同一个循环中一起使用break
和continue
语句。例如:
蟒蛇 101/第 11 章/休息和继续
while True:
value = input("\nEnter a number: ")
if value == 'q': # if input is 'q' exit from the while loop
print("Exiting program (break statement executed)...")
break
if not value.isdigit(): # if input is not a digit move on to the next iteration
print("Enter digits only (continue statement executed)")
continue
value = int(value)
print("Cube of", value, "is", value**3) # everything is fine, just print the cube
输出:
Enter a number: 5
Cube of 5 is 125
Enter a number: 9
Cube of 9 is 729
Enter a number: @#
Enter digits only (continue statement executed)
Enter a number: 11
Cube of 11 is 1331
Enter a number: q
Exiting program (break statement executed)...
上面的程序要求用户输入一个数字并计算它的立方。如果输入了一个数字,程序将显示该数字的立方。如果用户输入非数字字符,则执行continue
语句,跳过循环主体中剩余语句的执行,程序再次要求用户输入。另一方面,如果用户输入q
,则执行循环体中的break
语句,while 循环终止。
Python 中的列表
最后更新于 2020 年 9 月 21 日
顺序
Sequences 是一个通用术语,用于指代可以保存多项数据的数据类型。在 Python 中,我们有几种类型的序列,以下三种是最重要的:
- 目录
- 元组
- 用线串
在本章中,我们将讨论列表类型。
什么是列表?
假设我们要计算一个班级 100 个学生的平均分数。为了完成这项任务,我们的第一步是通过创建 100 个变量来存储 100 名学生的分数。目前为止一切顺利。如果我们要计算 1000 名或以上学生的平均分数会怎样?我们应该创建 1000 个变量吗?不要。当然不是。这种解决问题的方法是非常不切实际的。我们需要的是一份清单。
列表是由多个项目组成的序列,用逗号分隔,用方括号括起来,即[]
。创建列表的语法如下:
variable = [item1, item2, item3, ..., itemN]
存储在列表中的每一项都称为列表元素或简称为元素。例如:
>>>
>>> numbers = [11, 99, 66, 22]
>>>
该语句创建一个包含 4 个元素的列表,并将其分配给变量numbers
。请注意,就像其他所有东西一样,列表也是一个对象,类型为list
。numbers
变量不存储列表的内容,它只存储对列表对象实际存储在内存中的地址的引用。
>>>
>>> type(numbers)
<class 'list'>
>>>
要在 Python shell 中打印列表内容,只需键入列表名称。
>>>
>>> numbers
[11, 99, 66, 22]
>>>
我们也可以使用print()
功能打印列表。
>>>
>>> print(numbers)
[11, 99, 66, 22]
>>>
列表可以包含相同或不同类型的元素。
>>>
>>> mixed = ["a string", 3.14, 199] # list where elements are of different types
>>>
>>> mixed
['a string', 3.14, 199]
>>>
要创建一个空列表,只需键入没有任何元素的方括号。
>>>
>>> empty_list = [] # an empty list
>>>
我们也可以使用list()
构造函数创建列表。
>>>
>>> list1 = list() # an empty list
>>> list2 = list([3.2, 4, 0.12]) # again elements in a list can be of different types
>>> list3 = list(["@@", "###", ">>>"]) # you can use symbols too
>>> list4 = list("1234") # creating list from string
>>>
>>>
>>> list1
[]
>>>
>>> list2
[3.2, 4, 0.12]
>>>
>>> list3
['@@', '###', '>>>']
>>>
>>> list4
['1', '2', '3', '4']
>>>
>>>
列表的元素也可以是列表。
>>>
>>> list5 = [
... [33, 55, 77], # first element
... [99, 31, 64] # second element
... ]
>>>
>>>
>>> list5
[[33, 55, 77], [99, 31, 64]]
>>>
>>>
list5
包含两种类型的元素list
。这种类型的列表被称为列表或嵌套列表或多维列表。
使用 range()函数创建列表
range()
功能也可以用来创建长列表。回想一下range()
函数返回一个 iterable 类型的对象(要了解更多信息请点击此处,我们只需要创建一个列表,将这个 iterable 对象传递给list()
构造函数,如下所示:
>>>
>>> list1 = list(range(5))
>>> list1
[0, 1, 2, 3, 4]
>>>
>>>
range(5)
生成以下序列:
0, 1, 2, 3, 4
list()
函数然后使用这个序列中的数字创建一个列表。
下面是更多的例子:
例 1:
>>>
>>> list2 = list(range(1, 101)) ## create a list of numbers from 1 to 100
>>> list2
[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, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
>>>
>>>
例 2:
>>>
>>> list3 = list(range(0, 100, 10)) ## create a list of numbers from 0 to 100 with step value of 10
>>> list3
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>>
>>>
列出功能
下表列出了我们在处理列表时常用的一些函数。
功能 | 描述 |
---|---|
len() |
返回序列中元素的数量。 |
sum() |
返回序列中元素的总和。 |
max() |
返回序列中值最大的元素。 |
min() |
返回序列中值最小的元素。 |
>>>
>>>
>>> list1 = [1, 9, 4, 12, 82]
>>>
>>> len(list1) # find the length of the list
5
>>>
>>> sum(list1) # find the sum of the list
108
>>>
>>> max(list1) # find the greatest element in the list
82
>>>
>>> min(list1) # find the smallest element in the list
1
>>>
>>>
索引运算符
就像字符串一样,列表中的元素被0
索引,这意味着第一个元素在索引0
处,第二个在1
,第三个在2
处,以此类推。最后一个有效索引将比列表长度少一个。我们使用以下语法从列表中访问一个元素。
a_list[index]
其中index
必须是整数。
例如,下面的语句创建了一个包含 6 个元素的列表。
list1 = [88, 99, 4.12, 199, 993, 9999]
这里list1[0]
指的是元素88
,list1[1]
指的是99
,list[5]
指的是9999
。
>>>
>>> list1 = [88, 99, 4.12, 199, 993, 9999]
>>>
>>> list1[0] # get the first element
88
>>> list1[1] # get the second element
99
>>> list1[5] # get the sixth element
9999
>>>
我们还可以使用len()
函数计算列表的最后一个有效索引,如下所示:
>>>
>>> len(list1) - 1
5
>>>
>>> list1[len(list1) - 1] # get the last element
9999
>>>
试图访问超过最后一个有效索引的元素将导致IndexError
。
>>>
>>> list1[100] # get the element at index 100
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
>>>
就像字符串一样,负索引在这里仍然有效。事实上,我们可以在 Python 中的几乎所有类型的序列上使用 can 负索引。
从图中可以看到,最后一个元素在索引-1
处,第二个最后一个元素在-2
处,以此类推。第一个元素在索引-6
。
>>>
>>> list1
[88, 99, 4.12, 199, 993, 9999]
>>>
>>> list1[-1] # get the last element
9999
>>> list1[-2] # get the second last element
993
>>>
要计算第一个元素的指数,使用len()
函数,如下所示:
>>>
>>> list1[-len(list1)] # get the first element
88
>>>
列表是可变的
列表是可变的,这意味着我们可以在不创建新列表的情况下修改列表。考虑以下示例:
>>>
>>> list1 = ["str", "list", "int", "float"]
>>>
>>> id(list1) # address where list1 is stored
43223176
>>>
>>> list1[0] = "string" # Update element at index 0
>>>
>>> list1 # list1 is changed now
['string', 'list', 'int', 'float']
>>>
>>> id(list1) # notice that the id is still same
43223176
>>>
>>>
请注意,即使修改了列表,变量list1
的 id 也保持不变。这表明当我们在索引0
处分配新元素时,没有创建新的列表对象。
遍历列表中的元素
为了迭代一个列表,我们可以使用如下循环:
>>>
>>> marks = [122, 45, 23, 78, 65, 12]
>>> for m in marks:
... print(m)
...
122
45
23
78
65
12
>>>
在每次迭代中,从列表中为变量m
分配一个值。更改循环体中变量m
的值不会更新列表中的元素。因此,当我们不需要修改列表中的元素时,这个方法通常用于遍历列表。
要修改元素,我们可以结合range()
函数使用 for 循环,如下所示:
>>>
>>> marks = [122, 45, 23, 78, 65, 12]
>>>
>>> import random
>>>
>>> for i in range(len(marks)):
... marks[i] = random.randint(1, 100) # assign some random value between 1 to 100 to all elements
...
>>>
>>> marks
[59, 9, 59, 21, 75, 61]
>>>
>>>
虽然 for 循环是遍历列表的首选方式,但如果我们愿意,也可以使用 while 循环。例如:
>>>
>>> i = 0
>>>
>>> while i < len(marks):
... print(marks[i])
... i += 1
...
59
9
59
21
75
61
>>>
>>>
列表切片
我们在第课讨论的切片操作符 Python 中的字符串也可以在列表中找到。唯一的区别是,它不是返回一片字符串,而是返回一片列表。它的语法是:
list[start:end]
这将返回从索引start
到end - 1
的列表片段。以下是一些例子:
>>>
>>> list1 = [11, 33, 55, 22, 44, 89]
>>>
>>> list1[0:4]
[11, 33, 55, 22]
>>>
>>>
>>> list1[1:5]
[33, 55, 22, 44]
>>>
>>>
>>> list1[4:5]
[44]
>>>
start
和end
索引是可选的,如果没有指定,那么开始索引是0
,结束索引是列表的length
。例如:
>>>
>>> list1
[11, 33, 55, 22, 44, 89]
>>>
>>> list1[:2] # same as list1[0:2]
[11, 33]
>>>
>>> list1[2:] # same as list1[2:len(list1)]
[55, 22, 44, 89]
>>>
>>> list1[:] # same as list1[0:len(list1)]
[11, 33, 55, 22, 44, 89]
>>>
>>>
中的成员资格运算符,而不是中的
就像字符串一样,我们可以使用in
和not in
运算符来检查列表中是否存在某个元素。以下是一些例子:
>>>
>>> cards = ["club", "diamond", "heart", "spades"]
>>>
>>> "club" in cards
True
>>>
>>> "joker" in cards
False
>>>
>>> "pikes" not in cards
True
>>>
>>> "heart" not in cards
False
>>>
>>>
列表串联
使用+
操作符也可以加入列表。当两边的操作数都是列表时+
运算符通过组合两个列表中的元素来创建一个新列表。例如:
>>>
>>> list1 = [1,2,3] # create list1
>>> list2 = [11,22,33] # create list2
>>>
>>> id(list1) # address of list1
43223112
>>> id(list2) # address of list2
43223048
>>>
>>>
>>>
>>> list3 = list1 + list2 # concatenate list1 and list2 and create list3
>>> list3
[1, 2, 3, 11, 22, 33]
>>>
>>>
>>>
>>> id(list3) # address of the new list list3
43222920
>>>
>>>
>>> id(list1) # address of list1 is still same
43223112
>>> id(list2) # address of list2 is still same
43223048
>>>
>>>
请注意,串联并不影响list1
和list2
,它们的地址在串联前后保持不变。
连接列表的另一种方法是使用+=
运算符。+=
操作员修改列表,而不是创建新列表。这里有一个例子:
>>>
>>> list1
[1, 2, 3]
>>>
>>> id(list1)
43223112
>>>
>>> list1 += list2 # append list2 to list1
>>>
>>> list1
[1, 2, 3, 11, 22, 33]
>>>
>>>
>>> id(list1) # address is still same
43223112
>>>
语句list1 += list2
将list2
附加到list1
的末尾。注意list1
的地址还是没变。不像像 C、C++和 Java 这样的语言,数组是固定大小的。在 Python 中,列表是动态调整大小的。这意味着列表的大小会根据需要自动增长。
重复运算符
我们也可以对列表使用*
运算符。它的语法是:
sequence * n
*
操作符复制列表,然后加入它们。以下是一些例子:
>>>
>>> list1 = [1, 5]
>>>
>>>
>>> list2 = list1 * 4 # replicate list1 4 times and assign the result to list2
>>>
>>> list2
[1, 5, 1, 5, 1, 5, 1, 5]
>>>
>>>
*
运算符也可以用作复合赋值运算符*=
。唯一的区别是,它不是创建一个新的列表对象,而是更新现有的列表对象。
>>>
>>> action = ["eat", "sleep", "repeat"]
>>>
>>> id(action) # address of action list
32182472
>>>
>>> action *= 5
>>>
>>> action
['eat', 'sleep', 'repeat', 'eat', 'sleep', 'repeat', 'eat', 'sleep', 'repeat', '
eat', 'sleep', 'repeat', 'eat', 'sleep', 'repeat']
>>>
>>> id(action) # address is still the same
32182472
>>>
比较列表
就像字符串一样,我们可以使用关系运算符(>
、>=
、<
、<=
、!=
、==
)来比较列表。列表比较仅在涉及的操作数包含相同类型的元素时有效。该过程从比较两个列表中索引0
处的元素开始。只有当到达列表末尾或列表中对应的字符不同时,比较才会停止。
考虑以下示例:
>>>
>>> n1 = [1,2,3]
>>> n2 = [1,2,10]
>>>
>>>
>>> n1 > n2
False
>>>
以下是列表n1
和n2
比较涉及的步骤。
第一步:n1
的1
与n2
的1
比较。由于它们是相同的,接下来将对两个字符进行比较。
第二步:n2
的2
与n2
的2
进行对比。同样,它们是相同的,下面两个字符进行比较。
第三步:将n1
的3
与10
的10
进行比较。显然3
比10
小。所以比较n1 > n2
返回False
。
这里还有一个例子,其中的元素是字符串。
>>>
>>> word_list1 = ["pow", "exp"]
>>> word_list2 = ["power", "exponent"]
>>>
>>> word_list1 < word_list2
True
>>>
第一步:word_list1
的"pow"
与word_list2
的"power"
进行比较。显然"pow"
比"power"
小。此时,比较停止,因为我们发现列表中的元素不一样,所以比较word_list1 < word_list2
为真。
列表理解
通常,您需要创建列表,其中序列中的每个元素都是某些操作的结果,或者列表中的每个元素都满足某些条件。例如,创建一系列从50
到100
的数字立方体。我们在这种情况下使用列表理解。列表理解的语法是:
[ expression for item in iterable ]
以下是它的工作原理:
在每次迭代中item
从可迭代对象中被赋值,然后for
关键字之前的expression
被求值;expression
的结果随后用于产生列表的值。重复这个过程,直到没有更多的元素需要迭代。
这里有一个例子:
>>>
>>> cube_list = [ i**3 for i in range(50, 101) ]
>>>
>>> cube_list
[125000, 132651, 140608, 148877, 157464, 166375, 175616, 185193, 195112, 205379,
216000, 226981, 238328, 250047, 262144, 274625, 287496, 300763, 314432, 328509,
343000, 357911, 373248, 389017, 405224, 421875, 438976, 456533, 474552, 493039,
512000, 531441, 551368, 571787, 592704, 614125, 636056, 658503, 681472, 704969,
729000, 753571, 778688, 804357, 830584, 857375, 884736, 912673, 941192, 970299,
1000000]
>>>
我们还可以在列表理解中包含一个 if 条件,如下所示:
[ expression for item in iterable if condition ]
这和上面的完全一样,唯一的区别是for
关键字前的expression
只有在condition
为True
时才被评估。
这里有一个例子:
>>>
>>> even_list = [ i for i in range(1, 10) if i % 2 == 0 ]
>>>
>>> even_list
[2, 4, 6, 8]
>>>
列出方法
list
类有许多内置方法,允许我们添加元素、移除元素、更新元素等等。下表列出了list
类提供的一些操作列表的常用方法。
方法 | 描述 |
---|---|
appends(item) |
在列表末尾添加一个item 。 |
insert(index, item) |
在指定的index 处插入一个item 。如果指定的index 大于最后一个有效的index ,则item 被添加到列表的末尾。 |
index(item) |
返回指定item 第一次出现的索引。如果列表中不存在指定的item ,则会引发异常。 |
remove(item) |
从列表中删除指定item 的第一次出现。如果列表中不存在指定的item ,则会引发异常。 |
count(item) |
返回一个item 在列表中出现的次数。 |
clear() |
从列表中移除所有元素。 |
sort() |
按升序对列表进行排序。 |
reverse() |
颠倒列表中元素的顺序。 |
extend(sequence) |
将sequence 的元素追加到列表的末尾。 |
pop([index]) |
移除指定index 处的元素并返回该元素。如果未指定index ,则从列表中移除并返回最后一个元素。当index 无效时,会引发异常。 |
请注意,除了count()
之外,所有这些方法都会修改调用它的列表对象。
下面的 shell 会话演示了如何使用这些方法:
append()方法
>>>
>>> list1 = [1,2,3,4,5,6]
>>>
>>> id(list1)
45741512 # address of list1
>>>
>>> list1.append(10) # append 10 to list1
>>>
>>> list1
[1, 2, 3, 4, 5, 6, 10]
>>>
>>> id(list1) # address remains unchanged
45741512
>>>
insert()方法
>>>
>>> list1 = [1,2,3,4,5,6]
>>>
>>> id(list1)
45739272
>>>
>>> list1.insert(2, 1000) # insert item 1000 at index 2
>>>
>>> list1
[1, 2, 1000, 3, 4, 5, 6] # now the last valid index is 6
>>>
>>>
>>> list1.insert(6, 4000) # insert the item 4000 at index 6
>>>
>>> list1
[1, 2, 1000, 3, 4, 5, 4000, 6] # now the last valid index is 7
>>>
>>>
>>> list1.insert(8, 8000) # insert the item 8000 at index 8, which is beyond the last valid index
>>>
>>> list1
[1, 2, 1000, 3, 4, 5, 4000, 6, 8000]
>>> list1[8]
8000
>>>
index()方法
>>>
>>> list1 = [1, 2, 3, 4, 5, 6, 1, 2, 3]
>>>
>>> list1.index(1) # index of first occurrence of element 1
0
>>> list1.index(3) # index of first occurrence of element 3
2
>>> list1.index(90) # an exception is raised, as value 90 doesn't exists in the list
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 90 is not in list
>>>
>>>
remove()方法
>>>
>>> list1 = [1, 2, 3, 4, 5, 6, 1, 2, 3]
>>>
>>> list1.remove(1) # remove first occurence of element 1
>>>
>>> list1
[2, 3, 4, 5, 6, 1, 2, 3]
>>>
>>> list1.remove(2) # remove first occurence of element 2
>>>
>>> list1
[3, 4, 5, 6, 1, 2, 3]
>>>
>>> list1.remove(100) # an exception is raised, as value 100 doesn't exists in the list
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>>
>>>
count()方法
>>>
>>> list1 = [1, 2, 3, 4, 5, 6, 1, 2, 3]
>>>
>>> list1.count(2) # count the appearance of element 2 in the list
2
>>> list1.count(100) # count the appearance of element 100 in the list
0
>>> list1.count(1) # count the appearance of element 1 in the list
2
>>>
clear()方法
>>>
>>>
>>> list1 = [1, 2, 3, 4, 5, 6, 1, 2, 3]
>>>
>>> id(list1)
45738248
>>>
>>> list1.clear() # clear all the elements in the list list1
>>>
>>> list1
[]
>>>
>>> id(list1)
45738248
>>>
>>>
sort()方法
>>>
>>> list1 = [12, -2, 3, 4, 100, 50]
>>>
>>> list1.sort() # sort the list in ascending order
>>>
>>> list1
[-2, 3, 4, 12, 50, 100]
>>>
>>> types = ["str", "float", "int", "list"]
>>>
>>> types.sort() # sort the list, strings are sorted based on the ASCII values
>>>
>>> types
['float', 'int', 'list', 'str']
>>>
>>>
反向()方法
>>>
>>> list1 = [12, -2, 3, 4, 100, 50]
>>>
>>>
>>> list1.sort() # sort the list in ascending order
>>>
>>> list1
[-2, 3, 4, 12, 50, 100]
>>>
>>> list1.reverse() # sort the list in descending order
>>>
>>> list1
[100, 50, 12, 4, 3, -2]
>>>
>>>
扩展()方法
>>>
>>> list1 = [1, 2, 3]
>>>
>>> id(list1)
45738248
>>>
>>> list1.extend([100, 200, 300]) # append elements of list [100, 200, 300] to list1
>>>
>>> list1
[1, 2, 3, 100, 200, 300]
>>>
>>> id(list1)
45738248
>>>
>>>
>>> list1.extend("str") # We can pass strings too
>>>
>>> list1
[1, 2, 3, 100, 200, 300, 's', 't', 'r']
>>>
>>>
>>> id(list1)
45738248
>>>
>>>
pop()方法
>>>
>>> list1 = [1, 2, 3, 4, 5, 6]
>>>
>>> list1.pop(4) # remove the element at index 4
5
>>> list1
[1, 2, 3, 4, 6]
>>>
>>> list1.pop() # remove the last element
6
>>>
>>> list1
[1, 2, 3, 4]
>>>
>>>
>>> list1.pop(10) # index specified is not valid
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>>
>>>