上一篇我们介绍了列表的基本内容,包括如果创建列表、如何操作列表中元素,本篇内容我们将学习如何遍历列表并且在循环过程中处理某些操作
1、遍历整个列表
def print_hi():
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
输出
alice
david
carolina
2、在for循环中执行更多操作
例如在下面示例中我们打印每一个魔术师名次,并打印一些描述信息
def print_hi():
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("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
3、在for循环结束后执行某些操作
描述:在for循环后面,没有缩进的代码都只执行一次,而不会重复执行
用处:在for循环结束后需要提供总结性输出或接着执行程序必须完成的其他任务使用。
示例:
def print_hi():
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("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!
提示
1、for循环中不要遗漏冒号
2、该缩进的时候缩进,避免异常出输出和错误
4、创建数值列表
(1)使用range()方法生成一系列数字的列表,函数range()让Python从你指定的第一个值开始数,并在到达你指定的第二个值后停止,示例如下
def print_hi():
for value in range(1,5):
print(value)
输出
1
2
3
4
(2)使用range()方法创建数字列表
将range()作为list()的参数,输出将为一个数字列表,其本质是使用list()将range()的结果转换为列表。
示例1:
def print_hi():
numbers = list(range(1,6))
print(numbers)
输出
[1, 2, 3, 4, 5]
示例2:指定range()的步长,例如创建10以内偶数列表
def print_hi():
numbers = list(range(2,11,2))
print(numbers)
输出
[2, 4, 6, 8, 10]
示例3:如何创建一个列表,其中包含前
10个整数(即1~10)的平方呢?在Python中,两个星号(**)表示乘方运算
def print_hi():
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
输出
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
总结:使用函数range()几乎能够创建任何需要的数字集,只需要我们更改range()方法的参数,并且在for循环中加入某些操作
3、对数字列表的统计
我们这里简单列出几个常用的方法min、max、sum,看下面示例
def print_hi():
digits = list(range(0,10,1))
print(digits)
print(min(digits))
print(max(digits))
print(sum(digits))
输出
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
9
45
5、列表解析
列表解析是将for循环和创建新元素的代码合并成一行,并自动附加新元素。
示例:
def print_hi():
squares = [value**2 for value in range(1,11)]
print(squares)
输出
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
6、使用列表的一部分–切片
(1)切片–使用[],并且在方括号内指定使用的第一个元素和最后一个元素的索引(不包括最后一个元素),中间用分号分隔,要输出列表中的前三个元素,需要指定索引0~3,这将输出分别为0、1和2的元素。
示例1
players = ['charles','martina','michael','florence','eli']
print(players[0:3])
输出
['charles', 'martina', 'michael']
示例2:没有指定第一个索引,Python将自动从列表开头开始。
def print_hi():
players = ['charles','martina','michael','florence','eli']
print(players[:4])
输出
['charles', 'martina', 'michael', 'florence']
示例3:获取列表指定索引后面的元素
def print_hi():
players = ['charles','martina','michael','florence','eli']
print(players[2:])
输出
['michael', 'florence', 'eli']
def print_hi():
players = ['charles','martina','michael','florence','eli']
print(players[-3:])
输出
['michael', 'florence', 'eli']
(2)遍历切片
场景:如果要遍历列表中的部分元素时,使用切片和for循环来实现,示例如下
def print_hi():
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
(3)复制列表
def print_hi():
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\n My friends's favorite foods are:")
print(friend_foods)
输出
```python
My favorite foods are:
['pizza', 'falafel', 'carrot cake']
My friends's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
分析:我们使用切片复制列表之后,使用append方法在新的列表追加元素,原列表my_foods中内容没有改变,而复制的friend_foods列表内容改变了。
很多人有可能会 friend_foods = my_foods,但这是行不通的,这样做只是让Python将新变量friend_foods关联到my_foods中的列表中,我们改一下程序,在看输出结果
def print_hi():
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\n My friends's favorite foods are:")
print(friend_foods)
输出
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
My friends's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']