遍历整个列表
magicians=['alice','david','carolina']
for magicia in magicians:
print(magician) #打印每个名字
print(magician.title()+",that was a great trick!") #打印以其名字抬头的消息
print("Thank you,eneryone,That was a great magic show!") #没有缩进的代码都只执行一次
创建数字列表
range() 生成一系列的数字,可生成任何规律的数字
for value in range(1,5):
print(value)
使用list()函数以及range()创建数字列表
numbers=list(range(1,6))
print(numbers)
even_numbers=list(range(2,11,2)) #添加双数,指定步长为2
print(even_numbers)
使用循环创建数字列表
squares=[]
for value in range(1,11):
squares.append(value**2) #添加平方根
对数字列表进行简单的统计计算
digits=[1,2,3,4,5,6,7,8,9,0]
min(digits) #最小数
max(digits) #最大数
sum(digits) #和
列表解析
squares=[value**2 for value in range(1,11)]
print(squares)
使用列表的一部分
切片
players=['charles','martina','michael','florence','eli']
print(players[0:3]) #打印前三名的元素
print(players[1:4]) #打印始于'martina',终于'florence'的元素
print(players[:4]) #打印从开头到'florence'的元素
print(players[2:]) #打印从第三个到最后的元素
print(players[-3:]) #打印最后三个元素
遍历切片
players=['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
复制列表
my_foods=['pizza','falafel','carrot cake']
~~#friend_foods=my_foods #错误~~
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_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)
元组
元组跟使用列表方法一样,但是值不可修改
定义元组
dimensions=(200,50)
print(dimensions[0])
print(dimensions[1])
遍历元组
dimensions=(200,50)
for dimension in dimensions:
pirnt(dimension)
修改元组变量
dimensions=(200,50)
for dimension in dimensions:
pirnt(dimension)
~~#dimensions[0]=10 错误~~
dimensions=(400,200) #只能重定
for dimension in dimensions:
pirnt(dimension)
总结
如何使用for循环遍历列表,如何通过缩进确定程序的结构;如何创建简单的数字列表以及如何对数字列表执行的一些操作;如何通过切片来使用列表的一部分跟复制列表;学习了元组(对不应变化的值提供了一定程度的保护)。