Python编程 从入门到实践 第四章 列表操作

1. 遍历列表

  1. 需要对列表中的每个元素都执行相同的操作时,可使用Python中的for循环
  2. 操作示例:
>>> magicians = ['alice','david','carolina']
>>> for magician in magicians:
...     print(magician)
...
alice
david
carolina

1.1 for循环

  1. 编写for循环时,用于存储列表每个值的临时变量,建议选择描述单个列表元素的有意义的名称,如下所示:
    for cat in cats:
    for dog in dogs:
    for item in list_of _items:
    上面的cat/dog/item就是针对单个列表元素有意义的临时变量名

1.2 for 循环操作

  1. 在代码行for语句后面,每个缩进的代码行都是循环的一部分,将针对列表中的每个值都执行一次
  2. 示例1:
>>> 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!
  1. 示例2:
>>> 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.

1.3 for 循环结束后的操作

  1. for循环结束后需要提供总结性输出或者接着执行程序必须完成的其他任务
  2. 在for循环后面,没有缩进的代码都只执行一次,而且不会重复执行
  3. cmd中演示如下:
>>> 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.

>>> print("Thank you,That was a great magic show!")
Thank you,That was a great magic show!
  1. pycharm中演示如下:
    备注:后面若有运行分两块显示,均为使用pycharm操作,不再复述,便于代码可读
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,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,That was a great magic show!

2. 避免常见错误

2.1 遗漏冒号

for循环语句遗漏了冒号,将导致语法错误

>>> magicians = ['alice','david','carolina']
>>> for magician in magicians
  File "<stdin>", line 1
    for magician in magicians
                             ^
SyntaxError: expected ':'

2.2 忘记缩进

下面演示中,print语句应缩却未缩

>>> magicians = ['alice','david','carolina']
>>> for magician in magicians:
... print(magician)
  File "<stdin>", line 2
    print(magician)
    ^
IndentationError: expected an indented block after 'for' statement on line 1

2.3 忘记缩进额外的代码行

下面演示中,第二个print语句应缩却未缩
代码是合法的,执行并未报错,但是从结果上看,犯了逻辑错误,不符合预期

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.

2.4 不必要的缩进

下面演示中,print语句无需缩进,因为其并不隶属于前一行代码

>>> message = "Hello Python world!"
>>>     print(message)
  File "<stdin>", line 1
    print(message)
IndentationError: unexpected indent

2.5 循环后不必要的缩进

下面演示中,第三个print语句无需缩进,它应是循环结束后的总结性语句
代码是合法的,执行并未报错,但是从结果上看,犯了逻辑错误,不符合预期

>>> 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,That was a great magic show!")
...
Alice,that was a great trick!
I can't wait to see your next trick,Alice.

Thank you,That was a great magic show!
David,that was a great trick!
I can't wait to see your next trick,David.

Thank you,That was a great magic show!
Carolina,that was a great trick!
I can't wait to see your next trick,Carolina.

Thank you,That was a great magic show!

3. 数字列表

列表非常适合于存储数字集合

3.1 range()

  1. range(起始数字,结尾数字,步长)
  2. 结尾数字在结果中不显示,只显示起始数字累加n个步长后最接近结尾数字的整数,是编程语言中常见的差一行为
  3. 步长不写默认为1
>>> for value in range(1,11):
...     print(value)
...
1
2
3
4
5
6
7
8
9
10
>>> for value in range(1,11,2):
...     print(value)
...
1
3
5
7
9

3.2 list(range())

  1. 使用list()将range()的结果转换为列表
>>> even_numbers = list(range(1,11,2))
>>> print(even_numbers)
[1, 3, 5, 7, 9]
  1. Python中两个**代表乘方运算
squares = []
for value in range(1,11,2):
    square = value**2
    squares.append(square)
print(squares)
[1, 9, 25, 49, 81]

3.3 max()/min()/sum()

专门用于处理数字列表的函数

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

3.4 列表解析

  1. 列表解析是将for循环和创建新元素的代码合成一行,并自动附加新元素
  2. 当你觉得编写三四行代码生成列表有点繁琐,就应考虑创建列表解析了
  3. 属于进阶内容
>>> squares = [value**2 for value in range(1,11,2)]
>>> print(squares)
[1, 9, 25, 49, 81]

4. 切片

是处理列表中的部分数据

4.1 切片介绍

  1. 下面冒号:左侧为起始索引编号,冒号:右侧为终止索引编号(右侧实际结果显示仍然具有差一行为)
>>> players =['charles','martina','michael','florence','eli']
>>> print(players[0:3])
['charles', 'martina', 'michael']

>>> players =['charles','martina','michael','florence','eli']
>>> print(players[0:5])
['charles', 'martina', 'michael', 'florence', 'eli']

>>> players =['charles','martina','michael','florence','eli']
>>> print(players[2:4])
['michael', 'florence']

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

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

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

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

4.2 遍历切片

遍历列表中的部分元素,可在for循环中使用切片

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

4.3 复制列表

  1. 要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:]
  2. 若friend_foods=my_foods[:] 更改为 friend_foods=my_foods 则这两个变量都指向同一个列表,结果完全一样,不符合我们要求
my_foods =['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
print("My favorite foods before are:")
print(my_foods)
print("My friend's favorite foods before are:")
print(friend_foods)

my_foods.append('cannoli')
friend_foods.append('ice cream')

print("\nMy favorite foods now are:")
print(my_foods)
print("My friend's favorite foods now are:")
print(friend_foods)
My favorite foods before are:
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods before are:
['pizza', 'falafel', 'carrot cake']

My favorite foods now are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods now are:
['pizza', 'falafel', 'carrot cake', 'ice cream']

5. 元组

  1. 列表时用于存储程序在运行期间可能变化的数据集
  2. 若是创建不可修改的元素的数据集,需要使用元组
  3. 不可改变的列表称为元组
  4. 元组使用圆括号标识,注意与列表使用中括号标识区分开来

5.1 定义元组

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

试图修改元组中的元素值,运行报错

>>> dimensions = (200,50)
>>> dimensions[0] = 250
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

5.2 遍历元组中的值

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

5.3 修改元组变量

虽然不能修改元组的元素,但可以给存储元组的变量重新赋值

dimensions = (200,50)
print("Orininal dimensions:")
for dimension in dimensions:
    print(dimension)
    
dimensions =(400,100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)
Orininal dimensions:
200
50

Modified dimensions:
400
100

6. 代码格式

  1. 让代码易于阅读有助你掌握程序是做什么的,也可以帮助他人理解你写的编码
  2. 代码被阅读的次数比写的次数多
  3. PEP8(Python改进提案)建议每级缩进使用四个空格
  4. 在程序中混合使用制表符和空格可能导致极难解决的问题,如果混合使用了,可以在编辑器重将文件中所有的制表符转为空格
  5. 建议每行代码不超过80字符
  6. 建议注释的行长不超过72字符
  7. 空行不会影响代码运行,但会影响代码的可读性

7. 章节跳转

  1. Python编程 从入门到实践 第一章 起步
  2. Python编程 从入门到实践 第二章 变量和简单数据类型
  3. Python编程 从入门到实践 第三章 列表简介
  4. Python编程 从入门到实践 第四章 列表操作
  5. Python编程 从入门到实践 第五章 if语句
  6. Python编程 从入门到实践 第六章 字典
  7. Python编程 从入门到实践 第七章 用户输入和while循环
  8. Python编程 从入门到实践 第八章 函数
  9. Python编程 从入门到实践 第九章 类
  10. Python编程 从入门到实践 第十章 文件和异常
  11. Python编程 从入门到实践 第十一章 测试代码
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值