Python基础(四)

Python(四)

操作列表

1.遍历整个列表

定义一个for循环,让Python从列表magicians中取一个名字,并与其变量magician相关联

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

输出结果:

alice
david
carolina

1.1深入研究循环

for magician in magicians:

这行代码让Python获取列表magicians中的第一个值’alice,并将其与变量magician相关联

接下来,Python读取下一行代码:

print(magician)

它让Python打印magician的值,依然是‘alice’

由于该列表中还包含其他值,Python返回到循环的第一行:

for magician in magicians:

Python获取列表中的下一个名字‘david’,并将其与变量magician相关联,然后在执行下面这行代码:

print(magician)

1.2在for循环中执行更多操作

magicians = ['alice','david','carolina']
for magician in magicians:
    print(f"{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.3在for循环结束后执行一些操作

magicians = ['alice','david','carolina']
for magician in magicians:
    print(f"{magician.title()},that was a great trick!")
print("Thank you ,everyone.That was a great magic show!")

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

输出结果:

Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
Thank you ,everyone.That was a great magic show!

2.避免缩进错误

2.1忘记缩进

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

函数调用print()应缩进却没有缩进。

输出结果:

File "D:\Python\pythonProject\myFirstPython.py", line 73
print(magician)
^
IndentationError: expected an indented block

Process finished with exit code 1

2.2不必要的缩进

message = "Hello Python world!"
    print(message)

函数调用print()无须缩进,因为它并非循环的组成部分。

输出结果:
File "D:\Python\pythonProject\myFirstPython.py", line 77
print(message)
^
IndentationError: unexpected indent

3.创建数值列表

3.1使用函数range()

for value in range(1,5):
    print(value)

输出结果:

1
2
3
4

在这个示例中,range()只打印1~4。函数range()让Python从指定的第一个数开始数,并到达指定的第二个值结束,输出不包含第二个值。

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

要将一组数转换为列表,可使用list():

numbers = list(range(1,6))
print(numbers)

输出结果:

[1, 2, 3, 4, 5]

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

例如,下面的代码打印1~10的偶数

even_numbers = list(range(2,11,2))
print(even_numbers)

输出结果:

[2, 4, 6, 8, 10]

在Python中,两个星号** 表示乘方运算。

下面的代码演示了如何将前10个整数的平方加入一个列表中:

squares = []    #创建了一个名为squares的空列表
for value in range(1,11):  #使用函数range()让Python遍历1~10的值
    square = value ** 2    #计算当前值的平方,并将结果赋给变量square
    squares.append(square)  #将新计算得到的平方值附加到列表squares末尾
print(squares)              #循环结束,打印列表squares

输出结果:

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

简洁地将代码附加到列表末尾:

squares.append(value**2)  

将for循环里面的两句合成一句。

输出结果:

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

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

digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))       #计算列表中的最小值并输出
print(max(digits))       #计算列表中的最大值并输出
print(sum(digits))       #计算列表所有元素的和并输出

输出结果:

0
9
45

4 使用列表的一部分

4.1 切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引。

与range()函数一样,Python不包含第二个索引,即到达第二个索引之前的元素后停止

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

输出结果:

['charles', 'martina', 'michael', 'florence']

如果没有指定第一个索引,Python将自动从头开始

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

输出结果:

['charles', 'martina', 'michael']

如果没有指定末尾索引,则自动到达列表末尾并包含末尾元素

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

输出结果:

['martina', '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

4.3 复制列表

my_food = ['pizza','falafel','carrot cake']  #创建一个喜欢的食物列表
friend_food = my_food[:]                     #创建一个新列表,从第一个列表中提取一个切片,赋给新列表
print("My favorite foods are:")
print(my_food)                                 #打印第一个列表
print("\nMy friend's favorite foods are:")
print(friend_food)                              #打印新列表

输出结果:

My favorite foods are:
['pizza', 'falafel', 'carrot cake']

My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']

如果将my_food直接赋给friend_food即

friend_food = my_food

会导致这两个变量相关联,不能单独进行操作

感兴趣的同学可以用append()函数去验证一下哦!

5 元组

Python将不能修改的值称为不可变的,而不可变的列表被称为元组。

5.1定义元组

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

输出结果:

200
50

如果尝试着修改一下元组中元素的值,会发生什么呢?

dimensions = (200,50)
dimensions[0] = 250
print(dimensions[0])

结果如下:

Traceback (most recent call last):
File "D:\Python\pythonProject\myFirstPython.py", line 120, in <module>
dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment

答案是:报错

5.2 遍历元组中的所有值

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

和遍历列表一样,Python返回元组中所有的元素:

200
50

5.3 修改元组变量

刚才不是说不能修改元组的元素吗?

其实:虽然不能修改元组的元素,但可以给存储元组的变量赋值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值