第3章 操作列表

3.1遍历整个列表

你经常需要遍历列表的所有元素,对每个元素执行相同的操作,对此可使用Python中的for循环。例如使用for循环来打印魔术师的名单:

magicians = ["alice","david","carolina"]
for magician in magicians:
   print(magician)

首先定义一个列表,接下来定义一个for循环,这行代码让python从列表magicians中取出一个名字,并将其与变量magician相关联。最后让python打印前面赋给变量magician的名字。

3.1.1深入研究循环

循环这种概念很重要,因为它是让计算机自动完成重复工作的常见方式之一。刚开始使用循环时请牢记,对列表中的每个元素都将执行循环指定的步骤,而不管列表包含多少个元素。如果列表包含一百万个元素,python就重复执行指定的步骤一百万次,其通常速度非常快。另外,编写for循环时,可以给依次与列表中每个值相关联的临时变量指定任意名称。然而,选择描述单个列表元素的有意义名称大有脾益。例如,对于小猫列表、小狗列表和一般性列表,像下面这样编译是个不错的选择:

for cat in cats:
for dog in dogs:

这些命名约定有助于你明白for循环中将对每个元素执行的操作。使用单数和复数式名称,可帮助你判断代码处理的是单个列表元素还是整个列表。

3.1.2在for循环中执行更多操作

在for循环中,可对每个元素执行任何操作。下面来拓展前面的示例:

magicians = ["alice","david","carolina"]
for magician in magicians:
   print(f"{magician.title()},that was a great trick!")
# 输出
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!

输出结果表明,对于列表中的每位魔术师,都打印了一条个性化消息。在for循环中想包含多少行代码都可以。每个缩进的代码行都是循环的一部分,将针对列表的每个值都执行一次。因此可以对列表中的每个值执行任意次数的操作。下面再添加一行代码,告诉每位魔术师,我们期待她的下一次表演:

magicians = ["alice","david","carolina"]
for magician in magicians:
   print(f"{magician.title()},that was a great trick!")
   print(f"i can/'t wait to see your next trick,{magician.title()}.\n")

在for循环中,想包含多少行代码都可以,实际上,你会发现使用for循环对每个元素执行众多不同的操作很有用。

3.1.3在for循环结束后执行一些操作

for循环结束后怎么办呢?通常你需要提供总结性输出或者接着执行程序所必须完成的其他任务。在for循环后没有缩进的代码都只执行一次,不会重复执行。

magicians = ["alice","david","carolina"]
for magician in magicians:
   print(f"{magician.title()},that was a great trick!")
   print(f"i can/'t wait to see your next trick,{magician.title()}.\n")
print("thank you,everyone.that was a great magic show!")
# 输出结果
Alice,that was a great trick!
i can/'t wait to see your next trick,Alice.

David,that was a great trick!
i can/'t wait to see your next trick,David.

Carolina,that was a great trick!
i can/'t wait to see your next trick,Carolina.

thank you,everyone.that was a great magic show!

使用for循环处理数据是一种对数据集执行整体操作的不错方式。

3.2避免缩进错误

python根据缩进来判断代码行与之前一个代码行的关系。简单的说,它要求你使用缩进让代码整洁而结构清晰。在较长的python程序中,你将看到缩进程度各不相同的代码块,从而对程序的组织结构有大致的认识。开始编写必须正确缩进的代码时,需要注意一些常见的缩进错误。例如程序员有时候会将不需要缩进的代码缩进,而对于必须缩进的代码却忘了缩进。查看这样的错误有助于以后避开它们,以及它们出现在程序中及时进行修复。

3.2.1忘记缩进

对于位于for语句后面且属于循环组成部分的代码行,一定要缩进。如果忘记缩进,python会提醒你:

magicians = ["alice","david","carolina"]
for magician in magicians:
print(magician)
# 提示
File "D:\ProgramAPPWords\Python\Project1\Chat3\test1.py", line 9
    print(magician)
    ^
IndentationError: expected an indented block after 'for' statement on line 8

通常将紧跟在for语句后面的代码行缩进,可消除这种缩进错误。

3.2.2忘记缩进额外的代码行

有时候,循环能够运行且不会报错,但结果可能出人意料。试图在循环中执行多项任务,却忘记缩进一些代码时就会出现这种情况。例如如果忘记缩进循环中的第二行代码(告诉每位魔术师期待他们的下次表演),就会出现这种情况:

magicians = ["alice","david","carolina"]
for magician in magicians:
   print(f"{magician.title()},that was a great trick!")
print(f"i can/'t wait to see your next trick,{magician.title()}.\n")
# 结果
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
i can/'t wait to see your next trick,Carolina.

最终的结果是只有最后一位魔术师收到消息,这是一个逻辑错误,虽然从语法上看,这些python代码是合法的,但由于存在逻辑错误,结果并不符合预期。

3.2.3不必要的缩进

如果你不小心锁进了无需缩进的代码行,python将指出这一点:

message = "hello python world"
    print(message)
# 提示
 File "D:\ProgramAPPWords\Python\Project1\Chat3\test1.py", line 13
    print(message)
IndentationError: unexpected indent

为避免意外缩进错误,请只缩进需要缩进的代码。只有要在for循环中对每个元素执行的代码需要缩进。

3.2.4循环后不必要的缩进

如果不小心锁进了应在循环结束后执行的代码,这些代码将针对每个列表元素重复执行。在有些情况下,这可能导致python报告语法错误,但在大多数情况下,这只会导致逻辑错误。例如:

magicians = ["alice","david","carolina"]
for magician in magicians:
   print(f"{magician.title()},that was a great trick!")
   print(f"i can/'t wait to see your next trick,{magician.title()}.\n")
   print("thank you,everyone.that was a great magic show!")
# 结果
Alice,that was a great trick!
i can/'t wait to see your next trick,Alice.

thank you,everyone.that was a great magic show!
David,that was a great trick!
i can/'t wait to see your next trick,David.

thank you,everyone.that was a great magic show!
Carolina,that was a great trick!
i can/'t wait to see your next trick,Carolina.

thank you,everyone.that was a great magic show!

这也是一个逻辑错误,python不知道你的本意,只要代码符合语法,它就会运行。

3.2.5遗漏了冒号

for语句末尾的冒号告诉我们下一行是循环的第一行。

magicians = ["alice","david","carolina"]
for magician in magicians
   print(magician)

如果不小心遗漏了冒号,将导致语法错误,因为python不知道你意欲何为,这种错误虽然易于消除,但并不是那么容易发现。

3.3创建数值列表

列表非常适合用于储存数字集合,而python提供了很多工具,可帮助你高效的处理数字列表。

3.3.1使用函数range( )

python函数range( ) 让你能够轻松的生成一系列数。例如:

for value in range(1,5):
    print(value)

在这个示例中,函数range( )只打印数1,2,3,4,这是编程语言常见的差一行为的结果。函数range( )让python从指定的第一个值开始数,并在到达你指定的第二个值时停止(不包含该值)。要打印1,2,3,4,5需使用range(1,6)。调用函数range( )时,也可只指定一个参数,这样它将从0开始。例如range(6)返回数1—5。

3.3.2使用range( )创建数字列表

要创建数字列表,可使用函数list( ) 将range( )的结果直接转换为列表。如果将range( )作为list的参数,输出将是一个数字列表。如下所示:

numbers = list(range(1,6))
print(numbers)
# 结果
[1,2,3,4,5]

使用函数range( )时,还可以指定步长。为此可给这个函数指定第三个参数,python将根据这个步长来生成数。

even_numbers = list(range(2,11,2))
print(even_numbers)
# 输出
[2,4,6,8,10]

使用函数range( )几乎能够创建任何需要的数集。下面演示如何将前十个整数的平方加入一个列表中:

squares = [ ]
for value in range(1,11):
     square=value**2
     squares.append(square)
print(squares)

3.3.3对数字列表执行简单的统计计算

有几个专门用于处理数字列表的python函数。例如,你可以轻松的找出数字列表的最大值、最小值和总和:

digits = [1,2,3,4,5,6,7,8,9,0]
a = min(digits)
b = max(digits)
c = sum(digits)
print(a,b,c)

3.3.4列表解析

前面介绍的生成列表的方式包含三四行代码,而列表解析让你只需要编写一行代码就能生成这样的列表。列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。如下所示:

squares = [value**2 for value in range(1,11)]
print(squares)

要使用这种语法,首先指定一个描述性的列表名,如squares,然后指定一个左方括号,并定义一个表达式,用于生成要储存到列表中的值。在这个示例中,表达式为value**2,它计算平方值。接下来编写一个for循环,用于给表达式提供值,再加上右方括号。在这个示例中,for循环为for value in range(1,11),它将值提供给表达式。
注意: 这里的for语句末尾没有冒号。

3.4使用列表的一部分

3.4.1切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数range( )一样,python在到达第二个索引之前的元素后停止。

players = ["charles","martina","michael","florence","eli"]
print(players[0:3])
# 输出
['charles', 'martina', 'michael']

如果没有指定第一个索引,python将自动从列表开头开始:

players = ["charles","martina","michael","florence","eli"]
print(players[:4])
# 输出
['charles', 'martina', 'michael', 'florence']

要让切片终止于列表末尾,也可使用类似的语法:

players = ["charles","martina","michael","florence","eli"]
print(players[2:])
# 输出
['michael', 'florence', 'eli']

无论列表多长,这种语法都能够让你输出从特定位置到列表末尾的所有元素。上一章说过,负数能够返回离列表末尾相应距离的元素,因此你可以输出列表末尾的任意切片。例如:

players = ["charles","martina","michael","florence","eli"]
print(players[-3:])
# 输出
['michael', 'florence', 'eli']

注意: 可在表示切片的方括号内指定第三个值,这个值告诉python在指定范围内每隔多少元素提取一个。

3.4.2遍历切片

如果要遍历列表的部分元素,可在for循环中使用切片,如下所示:

players = ["charles","martina","michael","florence","eli"]
print("here are the first three players on my team:")
for player in players[:3]:
    print(player.title())

3.4.3复制列表

我们经常需要根据既有列表创建全新的列表。下面来介绍复制列表的工作原理。要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引。例如L:

my_foods = ["pizza","falafel","carrot cake"]
friend_foods = my_foods[:]
print("my favorite foods are:")
print(my_foods)
print("\nmy friend's favorite foods are:")
print(friend_foods)
# 输出结果
my favorite foods are:
['pizza', 'falafel', 'carrot cake']

my friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']

为核实确实有两个列表,下面在每个列表中都添加一种食品,并进行核实:

my_foods.append("cannoli")
friend_foods.append("ice cream")
print("my favorite foods are:")
print(my_foods)
print("\nmy friend's favorite foods are:")
print(friend_foods)
# 输出结果
my favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']

my friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']

3.5元组

列表非常适合用于储存在程序运行期间可能变化的数据集。列表是可以修改的,然而有时候你需要创建一些列不可修改的元素,元组可以满足这种需求。python将不能修改的值称为不可变的,而不可变的列表称为元组。

3.5.1定义元组

元组看起来很像列表,但使用圆括号而非中括号来标识。定义元组后,就可使用索引来访问其元素,就像访问列表元素一样。例如:

dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])

注意:严格地说,元组是由逗号标识的,圆括号只是让元组看起来更整洁、更清晰。如果你要定义只含有一个元素的元组,必须在这个元素后面加上逗号:

my_t=(3,)

3.5.2遍历元组中的所有值

像列表一样,也可以使用for循环来遍历元组中的所有值:

dimensions = (200,50)
for dimension in dimensions:
    print(dimension)

修改元组变量

虽然不能修改元组的元素,但可以给储存元组的变量赋值。如下所示:

dimensions = (200,50)
print("original dimensions:")
for dimension in dimensions:
    print(dimension)
dimensions = (400,100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)
# 输出
original dimensions:
200
50

Modified dimensions:
400
100

相比于列表,元组是更简单的数据结构。如果需要储存的一组值在程序的整个生命周期内都不变,就可以使用元组。

3.6设置代码格式

随着你编写的程序越来越长,有必要掌握一些代码格式的设置约定。

3.6.1缩进

PEP 8建议每级缩进四个空格。这即可提高可读性,又留下了足够的多级缩进空间。

3.6.2行长

很多程序员建议每行不超过80字符,最初制定这样的指南时,在大多数计算机中,终端窗口每行只能容纳79字符,当然现在可容纳字符有所增加,PEP 8还建议注释的行长不超过72字符。

3.6.3空行

要将程序的不同部分分开,可使用空行,你应该使用空行来组织程序文件,但也不能滥用。

你可能感兴趣的:(python学习笔记,前端,数据结构,python)