四、操作列表

1. 遍历

magicians = ['alice', 'david', 'carolina']

# (1) 注意:末尾有冒号
# (2) 使用单数和复数式名称,可帮助你判断代码处理的是单个列表元素还是整个列表
# (3) for循环里定义的变量,出了循环也能用
for magician in magicians:
	# 注意:前面要缩进
	# Python根据缩进来判断代码行与前一个代码行的关系
	# a. for后面每个缩进的代码行都是循环的一部分
	# b. for后面没有缩进的代码都只执行一次
	# b. 紧跟在for语句后面的代码行不缩进会报错
    print(magician)

=>

alice
david
carolina

2. 数值列表

(1) range()

# 1) 生成一系列数字
# 注意:输出不含第二个参数:5
for value in range(1, 5):
     print(value)

=>

1
2
3
4

# 2) 生成的不是list,可用list()将其结果转换为list
numbers = list(range(1, 6))
print(numbers) => [1, 2, 3, 4, 5]

# 3) 可指定步长
even_numbers = list(range(2, 11, 2))
print(even_numbers) => [2, 4, 6, 8, 10]

# 4) 应用:创建1~10的平方的列表
squares = []
for value in range(1, 11):
    squares.append(value ** 2)
print(squares) => [1, 4, 9, 16, 25, 36, 47, 64, 81, 100]

(2) 统计计算

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

# 注意:没有avg(),已试
min(digits) => 0
max(digits) => 9
sum(digits) => 55

(3) 列表解析

将for循环和创建新元素的代码合并成一行,并自动附加新元素

# 注意:末尾无冒号
 squares = [value ** 2 for value in range(1, 11)]

3. 切片

列表的部分元素

players = ['charles', 'martina', 'michael', 'florence', 'eli']

# 指定第一个和最后一个元素的索引,在到达第二个索引前的元素后停止
print(players[0:3]) => ['charles', 'martina', 'michael']

# 若未指定第一个索引,将从列表开头开始
print(players[:4]) => ['charles', 'martina', 'michael', 'florence']

# 省略终止索引,将终止于列表末尾
print(players[2:]) => ['michael', 'florence', 'eli']
print(players[-3:]) => ['michael', 'florence', 'eli']

遍历切片

for player in players[:3]:
    print(player.titile())

=>

Charles
Martina
Florence

4. 复制列表

[:] 创建包含整个列表的切片

  • 若只是简单地赋值,就不能得到两个列表,而是关联,即都指向同个列表

5. 元组

不可变的列表,对不应变化的值提供了一定程度的保护

# 用圆括号来标识,用索引访问其元素
dimensions = (200, 50)
print(dimensions[0]) => 200
print(dimensions[1]) => 50


# 修改元素会返回类型错误消息
dimensions[0] = 250
=>
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment


# 用for循环遍历
for dimension in dimensions:
    print(dimension)

=>

200
50


# 虽不能修改元组元素,但可以给存储元组的变量赋值,即重新定义
dimensions = (400, 100)
for dimension in dimensions:
    print(dimension)

=>

400
100    

6. 代码格式

1. 缩进

  • 建议每级缩进4个空格
  • 可设置编辑器,使其在文档中使用制表符键时插入空格而不是制表符

2. 空行

  • 要将程序的不同部分分开,可使用空行
  • 空行不影响代码的运行,但会影响代码可读性
  • Python解释器根据水平缩进情况来解读代码,但不关心垂直间距
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值