第四章 操作列表

遍历整个列表

在网站中,可能要对元素执行相通的操作,这个时候就要建立for循环

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

深入研究循环

1、刚开始使用循环时要牢记,对列表的每个元素,都将执行循环指定的步骤,不管列表包含什么元素

2、编写for循环的时候对于用于储存列表的每个值的临时变量,可以指定任何名称。对于列表名称更倾向于描述列表内容。使用单数和复试列表,可以帮助更好的判断代码写的是单个列表元素还是多个列表元素。

在for循环中执行更多操作

在for循环中可以对每个元素执行任何操作,来扩展前面的示例。

magicians=['alice','david','carolina']
for magician in magicians:
    print(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(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.
'''

在for循环结束后执行一些操作

在for循环后面 没有缩进的代码都只执行一次,且不会重复执行

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

避免缩进错误

忘记缩进

位于for语句后并且属于循环组成部分的代码行,一定要缩进,如果忘记缩进,代码行会提示

magicians=['alice','david','carolina']
for magician in magicians:
    print(magician.title() + ", that was a great trick!")
#IndentationError: expected an indented block

忘记缩进额外的代码行

有时候循环可以运行而不会报告错误,但是代码的输出并不是要求的。

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!
David, that was a great trick!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

'''

不必要的缩进

如果不小心缩进了无需缩进的代码,python会指出循环后不必要的缩进

message="Hello Python world!"
print(message)
#IndentationError: unexpected indent

循环后不必要的缩进

有可能是语法错误,但是大多数情况下是逻辑错误。

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

遗漏了冒号

python会提示下一行是循环的第一行

magicians=['alice','david','carolina']
for magician in magicians
    print(magician.title() + ", that was a great trick!")
    #SyntaxError: invalid syntax

创建数值列表

使用函数range()可以让你轻松生成一系列的数字

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

    '''

使用range()函数创建列表

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

numbers=list(range(1,10))
print(numbers)
#[1, 2, 3, 4, 5, 6, 7, 8, 9]

使用函数range()时可以指定步长

numbers=list(range(1,10,2))
print(numbers)
#[1, 3, 5, 7, 9]

使用函数range()几乎能够创建任何需要的数字集,例如,如何创建一个列表,其中包含前10个整数,

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]

使代码更简洁

squares=[]
for value in range(1,11):
    squares.append(value**2)
print(squares)
#[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

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

python有专门处理数字列表的函数,可以轻松找出数字列表的最大值和最小值以及总和


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

'''

列表解析

使用这种语法,要首先设定变量名,如squares,然后指定一个左右括号,并定义一个表达式,用于生成你要储存到列表的值

squares=[x**2 for x in range(10)]
print(squares)
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

使用列表的一部分

切片

players=['charles','martina','michael','florence','eli']
print(players[0:3])
#players[起始索引:终止索引]0~2
#['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[0:])
#['charles', 'martina', 'michael', 'florence', 'eli']

负数索引可以返回离列表末尾相应的元素,因此可以输出列表末尾的任何切片


players=['charles','martina','michael','florence','eli']
print(players[-3:])
#['michael', 'florence', 'eli']

遍历切片

要遍历全部列表的全部元素,可以使用for循环中来使用切片,在下面的示例中,我们遍历前三队员,并打印他们的名字。

players=['charles','martina','michael','florence','eli']
print("This is my team:")
for player in players[:3]:
    print(player)
    '''
This is my team:
charles
martina
michael

'''

复制列表

复制列表,可以创建一个包含整个列表的切片,方法是同时省略开始索引和结束索引,即[:]

假设有一个列表,其中包含你最喜欢的三种食物,想再创建一个列表来阐述你朋友的喜好,但是你朋友喜欢的也是你喜欢的所以可以复制列表来解决

my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_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']
'''

元组

定义元组

列表特别适合用于储存在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网站的用户列表或者游戏中的角色列表至关重要,但是有时候又需要创建一系列不可修改的元素,元组可以满足这种需求。

元组看起来犹如列表,但使用圆括号而不是方框号来标识,定义元组后,就可以使用索引来访问其元素

如果有一个大小不应该改变的矩形可以将其的长度和宽度储存在一个元组里,从而确保其不会被更改。

dimensions= (200, 50)
print(dimensions[0])
print(dimensions[1])
#200
#50

修改其中一个元素

dimensions= (200, 50)
dimensions[0]=300
#TypeError: 'tuple' object does not support item assignment
print(dimensions[0])
print(dimensions[1])
#200
#50

遍历元组中的所有值

像列表一样,也可以使用for循环来遍历元组中的所有值

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

修改元组变量

虽然不能修改元组的元素但是可以给储存元组的变量赋值。因此,如果要修改前述的矩形的尺寸,可以重新定义整个元组:

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

    '''

相对于列表,元组是更简单的数据结构,如果要储存的一组值在程序的整个生命周期都可以不变,可使用元组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值