目录
一、遍历整个列表(for循环)
经常会需要遍历列表的所有元素。若需要对列表中的每个元素执行相同的操作时,可用python中的for循环。在for语句末尾的冒号:不要遗漏,for语句后的print( )需要缩进。
如果有一个长长的魔术师名单,要将每个魔术师的名单打印出来,若分别获取每个名字,则会包括大量重复代码,同时如果名单长度发生变化,还需修改代码。故使用for循环。
magicians=['alice','david','carolina']
for magician in magicians: #先定义循环,在列表magicians中取出一个名字,与magician关联
print(magician)
alice
david
carolina
1.简单理解for循环
python首先读取第一行代码for magician in magicians——让Python获取列表magicians中的第一个值’alice',并将其与变量magician相关联。接下来,Python读取下一行代码print(magician) ——让Python打印其值。 鉴于该列表还包含其他值,Python返回到循环的第一行,直到for循环后无其他代码。
列表中的每个元素,都将执行循环指定的步骤,不管列表包含了多少个元素。使用单数和复数名称可以帮助你判断代码段处理的是单个列表元素还是整个列表。如for dog in dogs.每个缩进的代码行都是循环的一部分,将针对列表中的每个值都执行一次。
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!
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()都缩进了,故它们都将对列表中的每个魔术师执行一次。
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!
3.在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()都缩进了,故它们都将对列表中的每个魔术师执行一次。
print("Thank you,everyone.That was a great magic show!")
#第三个调用print没有缩进,故只执行了1次。若缩进,则会重复3次。
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()都缩进了,故它们都将对列表中的每个魔术师执行一次。第三个调用print没有缩进,故只执行了1次。
二、避免缩进的错误
python根据缩进来判断代码行与前一个代码行的关系,缩进可以让代码整洁而结构清晰。
1.忘记缩进:紧跟在for语句后的代码行,调用print( )没有缩进。
IndentationError: expected an indented block
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!
3.不必要的缩进:只有要在for循环中对每个元素执行的代码需要缩进。
IndentationError: unexpected indent
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()}!")
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!
5.遗漏了冒号:将导致语法错误,python不知道你意欲何为。for语句末尾的冒号告诉Python,下一行是循环的第一行。
magicians=['alice','david','carolina']
for magician in magicians
print(magician)
SyntaxError: invalid syntax
三、创建数值列表
1.使用函数range( )
函数range能轻松生成一系列数。函数range( )让python从指定的第一个值开始数,并在指定的第二个值时停止,这是编程语言中常见的差一行为的结果。调用函数range( )时,也可只指定一个参数,这样它将从0开始。
for value in range(1,5):
print(value)
1
2
3
4
for value in range(5):
print(value)
0
1
2
3
4
2.使用range( )创建数字列表
要创建数字列表,可用函数list( )将range( )的结果直接转为列表。只用函数range( )只会把一系列数打印出来,要将数转为列表可用list( )。
numbers=(list(range(1,6)))
print(numbers)
[1, 2, 3, 4, 5]
!1和2的区别:1用for循环遍历了一系列数所以打印出来每一行都是数。 2用list( )所以是数的列表,故列表需要列表名。
使用range( )函数,可指定步长。所以可以给这个函数指定第三个参数,python依据步长来生成数
even_numbers=list(range(2,11,2)) #从2开始,终值小于11,不断加2
print(even_numbers)
[2, 4, 6, 8, 10]
使用range( )几乎可以创建任何需要的数集,如1-10的平方的列表,**表示乘方运算。不一定要用list( )才能创建列表,可以先创建空列表,在循环附加。
squares=[]
for value in range(1,11): #展开for循环,首先取出第一个数1
square=value**2 #对第一个数1进行平方,并与square关联
squares.append(square) #把平方数附加到列表中,开展下一个循环,直到执行完列表中的10
#第3行和第4行等价于 squares.append(value**2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3.对数字列表执行简单的统计计算
找出最大值:函数max( );找出最小值:函数min( );求和:函数sum( )。
>>> digits=[1,2,3,4,5,6,7,8,9,0]
>>> max(digits)
9
>>> min(digits)
0
>>> sum(digits)
45
4.列表解析
列表解析的作用:在已有列表的基础上形成新的列表(对已有列表平方运算,小写等);也可以通过建空列表[ ]再append()附加。若需要列表作其他用,可复制列表[:]。
列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。对列表的操作多规一。
首先指定一个描述性的列表名(squares),指定左括号、定义一个表达式用于生成要存储在列表中的值(value**2),编写for循环用于给表达式提供值(for value in range(1,11) 前店后厂,注意店、厂商品随意但要一致 如value),加上右括号。注:for语句末尾没有冒号。
squares=[value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
四、使用列表的一部分
1.切片
处理列表的部分元素称为切片。创建切片需要指定第一个元素和最后一个元素的索引,中间用冒号隔开,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[1:]) #从第2个元素到最后
print(players[-2:]) #从倒数第2个元素到最后
['martina', 'michael', 'florence', 'eli']
['florence', 'eli']
2.遍历切片
若要遍历列表的部分元素,可在for循环中使用切片。
players=['charles','martina','michael','florence','eli']
print("Here is the first three players on my team.")
for player in players[:3]: #遍历前3名队员
print(player)
Here is the first three players on my team.
charles
martina
michael
3.复制列表
复制列表:可创建一个包含整个列表的切片,方法是同时省略起止索引和终止索引( [:] ),即整个列表的副本。
使用切片时复制的列表:会得到两个不同的列表,因为使用切片创建了列表的副本。
my_foods=['cake','dessert','milk']
friend_foods=my_foods[:] #提取切片,创建列表的副本,并将该副本赋给变量friend_foods.
my_foods.append('apple')
friend_foods.append('orange')
print(f"My favorite foods are {my_foods}.")
print(f"My friend's favorite foods are {friend_foods}.")
My favorite foods are ['cake', 'dessert', 'milk', 'apple'].
My friend's favorite foods are ['cake', 'dessert', 'milk', 'orange'].
不使用切片时复制的列表:只会得到一个列表,因为关联。
my_foods=['cake','dessert','milk']
friend_foods=my_foods
#不是将my_foods的副本赋给friend_food,而是将friend_foods与my_foods关联,故只生成一个列表。
friend_foods.append('orange')
print(f"My favorite foods are {my_foods}.")
print(f"My friend's favorite foods are {friend_foods}.")
My favorite foods are ['cake', 'dessert', 'milk', 'apple', 'orange'].
My friend's favorite foods are ['cake', 'dessert', 'milk', 'apple', 'orange'].
!注意:当用列表的副本时结果出乎意料,确认是否使用切片复制了列表。
五、元组
列表经常用于存储在程序运行期间可能变化的数据集,因为列表是可以修改的。
然而,有时需要创建一系列不可修改的元素,元组可以满足这种需求。python将不可修改的值称为不可变的,不可变的列表称为元组。相比于列表,元组是更简单的数据结构,若存储的值在程序的整个生命周期内都不变,就可使用元组。
1.定义元组
元组看起来像列表,但使用圆括号( )来标识,而非中括号[ ],定义元组后,可用索引来访问元素。
dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])
200
50
尝试修改元组,返回类型错误消息。
dimensions=(200,50)
dimensions[0]=250 #尝试修改元组元素
TypeError: 'tuple' object does not support item assignment
注意:严格说,元组是由逗号识别,圆括号只是让列表看起来更整洁,若定义只包括一个元素的元组,必须在元素后加上逗号。如my_t=(3,)
2.遍历元组中的所有值
可用for循环遍历元组中的所有值。
dimensions=(200,50)
for dimension in dimensions:
print(dimension)
200
50
3.修改元组变量
虽不能修改元组的元素,但可以给存储元组的变量赋值,用相同的变量名不同的元素来替换。
dimensions=(200,50)
print('Original dimension:')
for dimension in dimensions:
print(dimension)
dimensions=(400,100) #将新元组关联到变量dimensions
print('Modified dimension:')
for dimension in dimensions:
print(dimension)
Original dimension:
200
50
Modified dimension:
400
100