Python编程从入门到实践(第2版)第四章 操作列表

本章介绍了Python编程中for循环的使用,如遍历列表、在循环中执行多个操作、避免缩进错误。通过示例展示了如何创建和使用数值列表,进行简单的统计计算,以及使用列表切片。此外,还讲解了元组的概念,包括定义、遍历和不可变性。学习者将学会如何高效地处理和操作列表,以及理解缩进在Python代码中的重要性。

4.1 遍历整个列表

需要对列表中每个元素都执行相同的操作时,可使用Python中的for循环。
下面使用for循环来打印魔术师名单中的所有名字:
输入:

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

输出:

alice
david
carolina

4.1.1 深入研究循环

for in 循环

for magician in magicians:#依次获取magicians的每一个元素值,并分别与magician关联,打印输出。

4.1.2 在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 magician in magicians后面,每个缩进的代码行都是循环的一部分,将针对列表的每个值都执行一次。因此,可对列表中的每个值执行任意次数的操作。
输入:

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!
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.

4.1.3 在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!

第三个输出print()函数没有缩进,因此只执行一次。

4.2 避免缩进错误

下面是一些常见的缩进错误。

4.2.1 忘记缩进

magicians = ['alice','david','carolina']
for magician in magicians:
print(magician) # for语句后面属于循环组成部分的代码行,忘记缩进了。

上面函数调用print()应缩进却没有缩进。会报错:

  File "magicians.py", line 3
    print(magician)
        ^
IndentationError: expected an indented block

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

4.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")

结果就会得到如下:只有最后一个关联的carolina收到信息“I can’t wait to see your next trick,Carolina.”

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.

上述属于存在逻辑错误,但结果并不符合预期的情况。需要特别加强注意。

4.2.3 不必要的缩进

message = "Hello Python world!"
    print(message)

函数调用print()无须缩进,因为它并非循环的组成部分。
会指出如下错误:

  File "magicians.py", line 23
    print(message)
    ^
IndentationError: unexpected indent

只缩进需要缩进的代码。在前面学习的程序中,只有要在for循环中对每个元素执行的代码需要缩进。

4.2.4 循环不必要的缩进

输入:

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!

原本只需要执行一次的操作执行了多次。若不是你本意,则需要对执行该操作的代码取消缩进。

4.2.5 遗漏了冒号

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

magicians = ['alice','david','carolina']
for magician in magicians #遗漏了冒号
    print(magician) 

上面的错误在于遗漏了冒号,将导致语法错误。

动手试一试

练习4-1:比萨
用for循环把每种披萨的名称打印出来
输入:

Pizzas = ['pisa1','pisa2','pisa3']
for Pizza in Pizzas:#用for循环把每种披萨的名称打印出来
    print(Pizza)

输出:

pisa1
pisa2
pisa3

用for循环把包含每种披萨名称的句子打印出来,并最后在程序末尾添加一行代码作喜爱披萨的一句总结。
输入:

Pizzas = ['pisa1','pisa2','pisa3']
for Pizza in Pizzas:
    print(f"I like eat {Pizza}.")
print("I really love pizza!")

输出:

I like eat pisa1.
I like eat pisa2.
I like eat pisa3.
I really love pizza!

4.3 创建数值列表

4.3.1 使用函数range()

range()函数可以轻松打印一系列数。
输入:

for value in range(1,5): #打印1、2、3、4
    print(value)
for value in range(1,6): #打印1、2、3、4、5
    print(value)

输出:

1
2
3
4
1
2
3
4
5

调用函数range()时,也可只指定一个参数,这样它将从0开始。例如range(6)返回数0~5

for value in range(6):
        print(value)
0
1
2
3
4
5

4.3.2 使用函数range()创建数字列表

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

将1~5的这组数字转换为数字列表:
输入:

numbers = list(range(1,6)) #使用list()转换为数字列表
print(numbers)

输出:

[1, 2, 3, 4, 5]

建立一个从2开始直到11的偶数数字列表:
输入:

even_numbers = list(range(2,11,2))
print(even_numbers)

输出:

[2, 4, 6, 8, 10]

建立一个列表,其中包含前10个整数(1~10)的平方:
输入:

squares = []
for value in range(1,11): # 分别赋予1~10的数值
    squares.append(value**2) # 分别把(1~10)平方加载到空格列表中

print(squares)

输出:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

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

找出数字列表的最大值、最小值和总和:
输入:

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

输出:

0
9
45

4.3.4 列表解析

列表解析是将for循环和创建新元素的代码合并成一行,并自动附加新元素。
下面的示例使用列表解析创建你在前面看到的平方数列表:
输入:

squares = [value**2 for value in range(1,11)] 
#指定列表名aquares,指定一个左方括号,定义表达式value**2计算平方值,for循环用于给表达式提供值,再加右方括号
print(squares) # for循环为for value in range(1,11),它将值1~10提供给表达式value**2.
# 注意,这里的for语句末尾没有冒号

输出:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

创建自己的列表解析,需要经过一定的练习,往往可以代替三四行代码。

动手试一试

练习 4.3:数到20
使用一个for循环打印数1~20(含)
输入:

for value in range(1,21): #
    print(value)

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

练习 4-4:一百万求和
输入:

numbers = list(range(1,1000000))
print(min(numbers))
print(max(numbers))
print(sum(numbers)) #1~1000000内的数字相加求和

输出:

1
999999
499999500000

练习4-5:奇数
输入:

uneven_numbers = []
for value in range(1,20,2): #用for循环把1~20的奇数打印出来
    uneven_numbers.append(value)
    
print(uneven_numbers)

输出:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

练习4-6:3的倍数
输入:

uneven_numbers = []
for value in range(3,30,3):#用for循环把3~30的能被3整除的数打印出来
    uneven_numbers.append(value)

print(uneven_numbers)

输出:

[3, 6, 9, 12, 15, 18, 21, 24, 27]

练习4-7:立方
输入:

uneven_numbers = []
for value in range(1,10):#用for循环把1~10的能立方的数打印出来
    uneven_numbers.append(value**3)

print(uneven_numbers)

输出:

[1, 8, 27, 64, 125, 216, 343, 512, 729]

4.4 使用列表的一部分

4.4.1 切片

要创建切片,可指引要使用的第一个元素和最后一个元素的索引。
输入:

players = ['charles','martina','michael','florence','eli']
print(players[0:3]) # 打印第一、第二和第三个元素
print(players[1:4]) # 打印第二、第三和第四个元素
print(players[:4])  # 没有指引第一个索引,会自动从列表开头开始
print(players[2:])  # 打印从第三个元素到列表末尾的所有元素,可将起始索引指定为2,并省略终止索引
print(players[-3:]) # 打印输出从倒数第三名队员到最后的所有队员

输出:

['charles', 'martina', 'michael']
['martina', 'michael', 'florence']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']

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

4.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())

输出:

Here are the first three players on my team:
Charles
Martina
Michael

4.4.3 复制列表

假设有一个列表包含你最喜欢的四种食品,而你想再创建一个列表,并在其中包含一位朋友喜欢的所有食品。
输入:

my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:] # 不指定索引情况下从my_foods中提取一个切片,复制赋给变量friend_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 = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]

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']

而不使用切片的情况下复制列表的情况,如下所示:
输入:

my_foods = ['pizza','falafel','carrot cake']

# 这行不通:
friend_foods = my_foods

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', 'ice cream']
My friend's favorite foods are: # 输出显示,这两个列表是相同的,这并非我们想要的结果。
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

动手试一试

练习4-10:切片
输入:

players = ['charles','martina','michael','florence','eli']
print("The first three items in the list are:")
print(players[0:3]) # 打印前三个元素
print("Three items from the middle of the list are:")
print(players[1:4]) # 打印中间三个元素
print("The last three items in the list are:")
print(players[-3:]) # 打印末尾三个元素

输出:

The first three items in the list are:
['charles', 'martina', 'michael']
Three items from the middle of the list are:
['martina', 'michael', 'florence']
The last three items in the list are:
['michael', 'florence', 'eli']

练习4-11:你的披萨,我的披萨
输入:

Pizzas = ['pisa1','pisa2','pisa3']
friend_foods = Pizzas[:]
Pizzas.append('pisa4') # 在原披萨列表中添加一种披萨
friend_foods.append('pisa5') # 在副本列表中添加另一种披萨

print("My favorite pizzas are:")
for Pizza in Pizzas:
    print(Pizza)
print("My friend's favorite pizzas are:")
for friend_food in friend_foods:
    print(friend_food)

输出:

My favorite pizzas are:
pisa1
pisa2
pisa3
pisa4
My friend's favorite pizzas are:
pisa1
pisa2
pisa3
pisa5

4.5 元组

Python将不可变的列表称为元组。

4.5.1 定义元组

元组使用圆括号而非中括号来标识,定义元组后,同样可以使用索引来访问其元素。
输入:

dimensions = (200,50) # 使用圆括号而不是方括号,后续不允许修改第任何元素
print(dimensions[0]) # 打印第一个元素
print(dimensions[1]) # 打印第二个元素
my_t = (3,) # 定义只包含一个元素的元组

输出:

200
50

4.5.2 遍历元组中的所有值

输入:

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

输出:

200
50

4.5.3 修改元组变量

输入:

dimensions = (200,50) # 首先定义一个元组变量
print("Original dimensions:")`在这里插入代码片`
for dimension in dimensions:
    print(dimension)

dimensions = (400,100) # 再给元组变量重新赋值
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)

输出:

Original dimensions:
200
50
Original dimensions:
400
100

动手试一试

输入:

Restaurant_foods = ('apple','banana','orange','sugarcane','pear')
for Restaurant_food in Restaurant_foods:
    print(Restaurant_food)

Restaurant_foods = ('banana','orange','sugarcane','coffee','milky tea')
for Restaurant_food in Restaurant_foods:
    print(Restaurant_food)

输出:

apple
banana
orange
sugarcane
pear
banana
orange
sugarcane
coffee
milky tea

在本章中,学会了:
1.高效处理列表中元素;
2.如何使用for循环遍历列表;
3.Python如何根据缩进来确定程序的结构;
4.如何创建简单的数字列表以及对数字列表执行一些操作;
5.如何通过切片来使用列表的一部分·合复制列表;
6.还学会了元组
下一章中将会学习if语句。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值