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

for循环遍历整个列表

注意点:

编写for循环的时候,对于用于存储列表中每个值的临时变量,可以指定任何名称,最好是选择有意义的;

python根据缩进来判断代码行与前一个代码行的关系,同一个缩进的代码属于同一个等级;

不要遗漏for语句后的冒号:

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

注意,只打印到你指定的第二个值后停止。使用range(),如果输出不符号预期,请尝试将指定的值加一或者减一。

创建数字列表

可以将range()的输出结果输入到函数list()中,直接转换为列表。 

将1-10的平方的值加到一个列表里面去

 列表解析

要使用这种语法,首先指定一个描述性的列表名,如squares;然后指定一个左方括号,并定义一个表达式

# 4.1 遍历整个列表
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician)
    # 4.1.2 在for循环中执行更多的操作
    print(magician.title() + ", that was a great trick!")
    print("I cant't wait to see you next trick," + magician.title() + ".\n")
# 在for循环后面 没有缩进的代码都只执行一次
# python通过使用缩进让代码更容易读
print("Thank you,everyone.That was a great magic show!")

# 4.2 避免缩进错误
# 4.2.1 忘记缩进
magicians = ['alice', 'david', 'carolina']
# for magician in magicians:
# print(magician)
# IndentationError: expected an indented block
# 通常,将紧跟for语句后面的代码行缩进 可消除这种缩进错误
# 4.2.2 忘记缩进额外的代码行
for magician in magicians:
    print(magician.title() + ", that was a great trick")
print("I cant't wait to see your next trick,"+ magician.title() +".\n")
# 4.2.3 不必要的缩进
message = "Hello Python world"
#   print(message)  IndentationError: unexpected indent
# 只有要在for循环中对每个元素执行的代码需要缩进
# 4.2.4 循环后不必要的缩进
for magician in magicians:
    print(magician)
    # 4.1.2 在for循环中执行更多的操作
    print(magician.title() + ", that was a great trick!")
    print("I cant't wait to see you next trick," + magician.title() + ".\n")
    print("Thank you,everyone.That was a great magic show!")
print("4.2.5 遗漏了冒号")
# for magician in magicians
#     print(magician)  SyntaxError: invalid syntax
print("4.3 创建数值列表")
print("4.3.1 使用函数range()")
# range()函数让python从你指定的第一个值开始数 并到达你指定的第二个值后停止 因此输出不会包含第二个值
for value in range(1,5):
    print(value)
for value in range(1,6):
    print(value)
print("4.3.2 使用函数range()创建数字列表 可使用函数list将range()的结果直接转换成列表")
numbers = list(range(1, 6))
print(numbers)
# 使用函数range函数 还可指定步长
even_numbers = list(range(2, 11, 2))
print(even_numbers)
# 创建一个列表 其中包含前10个整数的平方呢
squares = []
for value in range(1, 11):
    square = value ** 2   # 两个**表示乘方运算
    squares.append(square)
print(squares)
squares = []
for value in range(1, 11):
    # 两个**表示乘方运算
    squares.append(value ** 2)  # 在循环中 计算每个值的平方 并立即将结果附加到列表的末尾
print(squares)
print("4.3.3 对数字列表执行简单的统计计算")
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
print("列表解析")
squares = [value**2 for value in range(1, 11)]
print(squares)
#######################################################################################
输出:
C:\Anaconda3\python.exe H:/python/venv/text
alice
Alice, that was a great trick!
I cant't wait to see you next trick,Alice.

david
David, that was a great trick!
I cant't wait to see you next trick,David.

carolina
Carolina, that was a great trick!
I cant't wait to see you next trick,Carolina.

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

alice
Alice, that was a great trick!
I cant't wait to see you next trick,Alice.

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

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

Thank you,everyone.That was a great magic show!
4.2.5 遗漏了冒号
4.3 创建数值列表
4.3.1 使用函数range()
1
2
3
4
1
2
3
4
5
4.3.2 使用函数range()创建数字列表 可使用函数list将range()的结果直接转换成列表
[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
4.3.3 对数字列表执行简单的统计计算
0
9
45
列表解析
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Process finished with exit code 0

 切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数range()一样,Python在到达你指定的第二个索引前面的元素后停止。

可以是用for循环来遍历切片的数据

可以是索引[:]来复制列表,如果简单的使用等于号来将一个列表赋值给另一个列表,可以理解为这两个列表都指向的是同一个列表空间,改变其中一个列表就会改变另一个。

# 4.4使用列表的部分元素-切片
print("4.4.1 切片")
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])

players = ['charles','martina','michael','eli']
print(players[1:])  # 如果没有指定最后一个位置,则一直切到尾部

# 如果没有指定第一个索引 python将自动从列表开头开始提取
players = ['charles', 'martina', 'michael', 'eli']
print(players[:3])
# 负数索引返回离列表末尾相应距离的元素
players = ['charles', 'martina', 'michael', 'eli']
print(players[-2:])

print("4.4.2 遍历切片")
players = ['charles', 'martina', 'michael', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())
print(players[:3]) # 与函数range()一样 在到达指定的第二个索引前面的元素后停止
print("可以是用for循环来遍历切片的数据")
players = ['charles', 'martina', 'michael', 'eli']
for player in players[1:4]:
    print(player)
print("4.4.3 复制列表")
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_food = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("My friend's foods are:")
print(friend_food)
# 可以是索引[:]来复制列表,如果简单的使用等于号来将一个列表赋值给另一个列表,
# 可以理解为这两个列表都指向的是同一个列表空间,改变其中一个列表就会改变另一个。
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("My friend's favorite foods are:")
print(friend_foods)
#####################################################################################
C:\Anaconda3\python.exe H:/python/venv/text
4.4.1 切片
['charles', 'martina', 'michael']
['martina', 'michael', 'eli']
['charles', 'martina', 'michael']
['michael', 'eli']
4.4.2 遍历切片
Here are the first three players on my team:
Charles
Martina
Michael
['charles', 'martina', 'michael']
可以是用for循环来遍历切片的数据
martina
michael
eli
4.4.3 复制列表
My favorite foods are:
['pizza', 'falafel', 'carrot cake']
My friend's foods are:
['pizza', 'falafel', 'carrot cake']
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']

Process finished with exit code 0

元组 

元组使用圆括号来标识,元组里面的元素不可增删,不可直接赋值修改!

可以是用for循环来遍历整个元组

虽然不能修改元组的元素,但可以给存储元组的变量赋值,因此,如果要修改,只能重新定义整个元组。

 

# 4.5 元组
# 4.5.1 定义元组
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
# TypeError: 'tuple' object does not support item assignment
# dimensions[0] = 250  由于试图修改元组的操作是被禁止的
# 4.5.2 遍历元组中的所有值
for dimension in  dimensions:
    print(dimension)
print("4.5.3 修改元组的变量")
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)
# 如果要修改前述矩阵的尺寸大小 可重新定义整个元组
dimensions = (200, 50)
print("Modifed dimensions:")
for dimension in dimensions:
    print(dimension)
####################################################################
C:\Anaconda3\python.exe H:/python/venv/text
200
50
200
50
4.5.3 修改元组的变量
Original dimensions:
200
50
Modifed dimensions:
200
50

Process finished with exit code 0

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值