使用for 循环来打印魔术师名单中的所有名字,
输入:
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician)
输出:
alice david carolina
在这个示例中,for 循环后面没有其他代码,因此程序就此结束。
在for 循环后面,没有缩进的代码都只执行一次,不会重复执行。
1.2 创建数值列表 1.2.1 使用函数range()
Python函数range() 让你能够轻松地生成一系列数,格式为:
range(begin,end,step)
begin为生成的第一个数,end是最后一个数,生成begin~end之间的数(不包括end),其中step为生成数的间隔(step需要大于0)。
若参数只有2个,则这俩个参数会传参给begin和end,step默认为1
若参数只有1个,则这个参数会传参给end,step默认为1,begin默认为0
若begin>end则不会生成任何数。
1.2.2 使用range() 创建数字列表输入:
numbers = list(range(1, 6)) print(numbers)
输出
[1, 2, 3, 4, 5]
另一个种方法,
输入:
squares = [value**2 for value in range(1, 11)] print(squares)
输出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]1.2.3 对数字列表执行简单的统计计算
输入:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(max(digits)) print(min(digits)) print(sum(digits))
输出:
9 0 45
1.3 使用列表的一部分 1.3.1 切片
要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数range()一样,Python在到达第二个索引之前的元素后停止。要输出列表中的前三个元素,需要指定索引0和3,这将返回索引为0、1和2的元素。
假设某列表名为players
players[begin::end]
如
输入:
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3])
输出:
['charles', 'martina', 'michael']
如果没有指定第一个索引,Python将自动从列表开头开始。
要让切片终止于列表末尾,也可使用类似的语法,不指定第二个索引。
都不填写会输出全部元素
若begin为负数时候,且end不填时候
会输出players中最后-begin个元素。-begin可以大于列表长度,若这样会输出全部元素
若end为负数时候,且begin不填时候
会输出players中前(end+len(players))个元素,若这个值小于0会输出空列表。
1.3.2 编历切片
输入:
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
1.3.3 复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:] )。形如:
my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:]
若不使用切片,如
输入:
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']
我们会发现此时会让friend_foods列表指向和my_foods,相当于一个引用,故不可取。
1.4 元组
定义元组:
dimensions = (200, 50)
输出元组:
print(dimensions[0])
严格地说,元组是由逗号标识的,圆括号只是让元组看起来更整洁、更
清晰。如果你要定义只包含一个元素的元组,必须在这个元素后面加上逗号。元组的元素的值不可以改变。
虽然不能修改元组的元素,但可以给存储元组的变量赋值。可重新定义整个元组:
输入:
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
其中元组的遍历和列表的遍历一样。
依旧可以是:
for dimension in dimensions: print(dimension)



