Python 从菜鸟到大咖的必经之路_Python 操作列表

大家好!
我是小黄,很高兴又跟大家见面啦 !
拒绝水文,从我做起 !!!!
如若转载 ,麻烦请注明出处!!!!

今天更新的是:


创建时间:2021年2月18日
重构时间: 2021年5月25号
软件: Python 3 、Pycharm


1. 遍历整个列表:

  • 你经常需要遍历列表的所有元素,对每个元素执行相同的操作。
  • 例如,在游戏中,可能需要将每个界面元素平移相同的距离;对于包含数字的列表,可能需要对每个元素执行相同的统计运算;
  • 在网站中,可能需要显示文章列表中的每个标题。需要对列表中的每个元素都执行相同的操作时,可使用Python中的for循环。
# 利用for 循环遍历整个列表:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician)

# alice
# david
# carolina
  • 刚开始使用循环时请牢记,对列表中的每个元素,都将执行循环指定的步骤,而不管列表包含多少个元素。如果列表包含一百万个元素,Python就重复执行指定的步骤一百万次,且通常速度非常快。
  • 另外,编写for循环时,对于用于存储列表中每个值的临时变量,可指定任何名称。然而,选择描述单个列表元素的有意义的名称大有帮助。

1.1 深入地研究循环:

  • 循环这种概念很重要,因为它是让计算机自动完成重复工作的常见方式之一
# 深入研究循环:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print("for "+magician+" in "+magician)

# for alice in alice
# for david in david
# for carolina in carolina

1.2 在 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!

# 这个循环第一次迭代时,变量magician的值为'alice',因此Python打印的第一条消息的抬头为'Alice'。
# 第二次迭代时,消息的抬头为'David',
# 而第三次迭代时,抬头为'Carolina'。
  • 在for循环中,想包含多少行代码都可以。在代码行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.
  • 由于两条print语句都缩进了,因此它们都将针对列表中的每位魔术师执行一次。第二条print语句中的换行符"\n"、在每次迭代结束后都插入一个空行,从而整洁地将针对各位魔术师的消息编组:

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

  • 在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!")

# 开头两条print语句针对列表中每位魔术师重复执行。然而,由于第三条
print语句没有缩进,因此只执行一次:    
# Alice, that was a great trick!
# I can't wait to see your next trick, Alice.
# 
# Thank you, everyone. That was a great magic show!
# David, that was a great trick!
# I can't wait to see your next trick, David.
# 
# Thank you, everyone. That was a great magic show!
# 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循环处理数据是一种对数据集执行整体操作的不错的方式。例如,你可能使用for循环来初始化游戏——遍历角色列表,将每个角色都显示到屏幕上;再在循环后面添加一个不缩进的代码块,在屏幕上绘制所有角色后显示一个Play Now按钮。

2. 避免缩进错误:

  • Python根据缩进来判断代码行与前一个代码行的关系。
  • Python通过使用缩进让代码更易读;简单地说,它要求你使用缩进让代码整洁而结构清晰。在较长的Python程序中,你将看到缩进程度各不相同的代码块,这让你对程序的组织构有大致的认识。
  • 当你开始编写必须正确缩进的代码时,需要注意一些常见的缩进错误。

例如,有时候,程序员会将不需要缩进的代码块缩进,而对于必须缩进的代码块却忘了缩进。通过查看这样的错误示例,有助于你以后避开它们,以及在它们出现在程序中时进行修复。

2.1 忘记缩进:

  • 对于位于for语句后面且属于循环组成部分的代码行,一定要缩进。如果你忘记缩进, Python会提醒你:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)

# File "magicians.py", line 3
# print(magician)
#      ^
# IndentationError: expected an indented block
  • 解决办法: 通常,将紧跟在for语句后面的代码行缩进,可消除这种缩进错误。

2.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!
# David, that was a great trick!
# 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!")
    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.

2.3 不必要的缩进:

  • 如果你不小心缩进了无需缩进的代码行, Python将指出这一点
message = "Hello Python world!"
 print(message)

# File "hello_world.py", line 2
# print(message)
# ^
# IndentationError: unexpected indent

# 为避免意外缩进错误,请只缩进需要缩进的代码。
#在前面编写的程序中,只有要在for循环中对每个元素执行的代码需要缩进。

2.4 循环后不必要的缩进:

  • 如果你不小心缩进了应在循环结束后执行的代码,这些代码将针对每个列表元素重复执行。在有些情况下,这可能导致Python报告语法错误,但在大多数情况下,这只会导致逻辑错误。
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.
#
# Thank you everyone, that was a great magic show!
# David, that was a great trick!
# I can't wait to see your next trick, David.
#
# Thank you everyone, that was a great magic show!
# 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!

2.5 遗漏了冒号:

# for 循环中遗漏了冒号:
magicians = ['alice', 'david', 'carolina']
for magician in magicians
print(magician)

#     for magician in magicians
#                             ^
# SyntaxError: invalid syntax

3. 创建数值列表:

  • 需要存储一组数字的原因有很多,例如,在游戏中,需要跟踪每个角色的位置,还可能需要跟踪玩家的几个最高得分。在数据可视化中,处理的几乎都是由数字(如温度、距离、人口数量、经度和纬度等)组成的集合。
  • 列表非常适合用于存储数字集合,而Python提供了很多工具,可帮助你高效地处理数字列表。明白如何有效地使用这些工具后,即便列表包含数百万个元素,你编写的代码也能运行得很好。

3.1 使用函数range():

  • Python函数range()让你能够轻松地生成一系列的数字。例如,可以像下面这样使用函数range()来打印一系列的数字:
# 使用range()函数生成数字:
for value in range(1,5):
    print(value)

# 1
# 2
# 3
# 4

在这个示例中:

  • range()只是打印数字1~4,这是你在编程语言中经常看到的差一行为的结果。函数range()让Python从你指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出不包含第二个值(这里为5)。
# 要打印数字1~5,需要使用range(1,6):
for value in range(1,6):
    print(value)

# 1
# 2
# 3
# 4
# 5

使用range()时,如果输出不符合预期,请尝试将指定的值加1或减1。

3.2 使用range()创建数字列表:

  • 要创建数字列表,可使用函数list()将range()的结果直接转换为列表。如果将range()作为list()的参数,输出将为一个数字列表。
# 1. 打印了一系列数字。将数字转换为一个列表,可使用list():
numbers = list(range(1,6))
print(numbers) # [1, 2, 3, 4, 5]

# 2. 使用函数range()时,还可指定步长。
# 例如,下面的代码打印1~10内的偶数:
even_numbers = list(range(2,11,2))
print(even_numbers)

# 函数range()从2开始数,然后不断地加2,直到达到或超过终值( 11),
# 因此输出如下:
# [2, 4, 6, 8, 10]
# 1. 如何创建一个列表,其中包含前10个整数(即1~10)的平方呢?
squares = []                        # 创建一个空列表
for value in range(1,11):           # 使用函数range()让Python遍历1~10的值
    square = value**2               # 在循环中,计算当前值的平方,并将结果存储到变量square中
    squares.append(square)          # 将新计算得到的平方值附加到列表squares末尾
    print(squares)                  # 打印列表squares

# [1]
# [1, 4]
# [1, 4, 9]
# [1, 4, 9, 16]
# [1, 4, 9, 16, 25]
# [1, 4, 9, 16, 25, 36]
# [1, 4, 9, 16, 25, 36, 49]
# [1, 4, 9, 16, 25, 36, 49, 64]
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 简略写法:
# 2. 如何创建一个列表,其中包含前10个整数(即1~10)的平方呢?
squares = []                        # 创建一个空列表
for value in range(1,11):           # 使用函数range()让Python遍历1~10的值
    squares.append(value**2 )       # 计算当前值的平方,将新计算得到的平方值附加到列表squares末尾
    print(squares)                  # 打印列表squares

# [1]
# [1, 4]
# [1, 4, 9]
# [1, 4, 9, 16]
# [1, 4, 9, 16, 25]
# [1, 4, 9, 16, 25, 36]
# [1, 4, 9, 16, 25, 36, 49]
# [1, 4, 9, 16, 25, 36, 49, 64]
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

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

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# 查找最小值:
min(digits)
print(min(digits))      # 0
# 查找最大值:
max(digits)
print(max(digits))      # 9
# 计算和:
sum(digits)
print(sum(digits))      # 45

3.3 列表解析:

  • 前面介绍的生成列表squares的方式包含三四行代码,而列表解析让你只需编写一行代码就能生成这样的列表。
    列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。
  • 面向初学者的书籍并非都会介绍列表解析,这里之所以介绍列表解析,是因为等你开始阅读他人编写的代码时,很可能会遇到它们。
# 如何创建一个列表,其中包含前10个整数(即1~10)的平方
squares = [value**2 for value in range(1,11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 1. 首先指定一个描述性的列表名,如squares
# 2. 指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值
# 3. 表达式为value**2,它计算平方值。
# 4. 接下来,编写一个for循环,用于给表达式提供值,再加上右方括号。
# 5. 在这个示例中,for循环为for value in range(1,11),它将值1~10提供给表达式value**2。
# 请注意,这里的for语句末尾没有冒号。

4. 使用列表的一部分:

4.1 切片:

  • 要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数range()一样,Python在到达你指定的第二个索引前面的元素后停止。
# 1. 输出列表中的前三个元素,需要指定索引0~3:
#             0           1       2           3           4
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) # ['charles', 'martina', 'michael']

# 2. 如果你要提取列表的第2~4个元素,可将起始索引指定为1,并将终止索引指定为4
print(players[1:4]) # ['martina', 'michael', 'florence']

# 3. 如果你没有指定第一个索引, Python将自动从列表开头开始:
print(players[:4]) # ['charles', 'martina', 'michael', 'florence']

# 4. 如果要提取从第3个元素到列表末尾的所有元素,可将起始索引指定为2,并省略终止索引:
print(players[2:]) # ['michael', 'florence', 'eli']

# 5. 如果你要输出列表上的最后三个,可使用切片
print(players[-3:]) # ['michael', 'florence', '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

例如:

  • 编写游戏时,你可以在玩家退出游戏时将其最终得分加入到一个列表中。然后,为获取该玩家的三个最高得分,你可以将该列表按降序排列,再创建一个只包含前三个得分的切片。
  • 处理数据时,可使用切片来进行批量处理;
  • 编写Web应用程序时,可使用切片来分页显示信息,并在每页显示数量合适的信息。

4.3 复制列表:

  • 你经常需要根据既有列表创建全新的列表。下面来介绍复制列表的工作原理,以及复制列表可提供极大帮助的一种情形。
  • 要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引( [:])。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。
  • 例如,假设有一个列表,其中包含你最喜欢的四种食品,而你还想创建另一个列表,在其中包含一位朋友喜欢的所有食品。不过,你喜欢的食品,这位朋友都喜欢,因此你可以通过复制来创建这个列表:
# 1. 首先创建了一个名为my_foods的食品列表
my_foods = ['pizza', 'falafel', 'carrot cake']
# 2. 然后创建了一个名为friend_foods的新列表
# 我们在不指定任何索引的情况下从列表my_foods中提取一个切片,从而创建了
# 这个列表的副本,再将该副本存储到变量friend_foods中。
friend_foods = my_foods[:]
# 3. 打印每个列表:
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']

下期更新预告:

  • 09 TIANCHI_Python_元组

推荐阅读 点击标题可跳转:


各位路过的朋友,如果觉得可以学到些什么的话,点个赞 再走吧,欢迎各位路过的大佬评论,指正错误,也欢迎有问题的小伙伴评论留言,私信。

每个小伙伴的关注都是本人更新博客的动力!!!
请微信搜索【 在下小黄 】文章更新将在第一时间阅读 !
在这里插入图片描述

博客中若有不恰当的地方,请您一定要告诉我。前路崎岖,望我们可以互相帮助,并肩前行!


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

在下小黄

ღ给个赞 是对小黄最大的支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值