先做些复习
改写Hello World变成函数
我们在001里学习了打印Hello World
# 程序007.001
print('Hello, World')
它是我们借助编程语言这种咒语向世界打招呼的一种方式
在002里我们学习了def来定义自己的函数,我们把这2课合在一起变成一个练习
上面的练习答案如下
# 程序007.002
def say_hello(name):
print(f'Hello, {name}')
say_hello('蚂蚁老师')
让我们根据最近一次完成作业的情况,给积极性比较高的同学们打个招呼
可以这样写
# 程序007.003
student1 = 'lu'
student2 = '大白菜'
student3 = '木木'
student4 = '逻辑'
student5 = '逆行者'
say_hello(student1)
say_hello(student2)
say_hello(student3)
say_hello(student4)
say_hello(student5)
作为一个辛勤的法师,我们定义了5个字符串变量——这真是太繁琐了!
list来挽救你
我们可以用list来消除这种繁琐,先看看AI给出的解释
list的用法
# 程序007.004
students = ['lu', '大白菜', '木木', '逻辑', '逆行者']
print(students)
上面的代码定义了一个列表,列表里列出了积极完成作业的同学的名字,我们可以通过序号来获取列表里的成员
# 程序007.005
print(students[1]) # 大白菜
print(students[3]) # 逻辑
细心的同学会发现,序号为1的同学是大白菜,为什么不是lu呢?
那么,如何知道列表的长度呢?我们可以调用Python提供的函数len,它传入一个列表,返回列表的长度
# 程序007.006
students_num = len(students)
print(students_num) # 5
所以上面定义的students列表长度为5
回答完课堂练习,让我们结合003课学习的for循环和range函数,打印积极完成作业同学列表
遍历list
除了同学们在作业里使用range函数通过列表序号来遍历,list本身还有一个快捷的遍历方式
# 程序007.007
def say_hello(name):
print('Hello, ', name)
students = ['lu', '大白菜', '木木', '逻辑', '逆行者']
for student in students:
say_hello(student)
这种方式可以直接取出list里的元素,唯一的缺点是丢失了列表的序号,它和range通常在不同的场景里使用
list常见操作
# 程序007.008
# 增加同学A
a = '同学A'
students.append(a)
print(students)
# 找到同学A的序号/索引
idx = students.index(a)
# 修改同学A为同学B
students[idx] = '同学B'
print(students)
# 删除同学B
del students[idx]
print(students)
# 把同学A放在第一个
students.insert(0, a)
print(students)
# 查找木木同学,和没这个人同学是否在列表里
print('木木' in students)
print('没这个人' in students)
# 错误示例:当序号/索引超出列表长度-1时,会抛出错误
students[999]
# 复制一个列表方法1
print(students)
copy_students = list(students)
print(copy_students)
copy_students[0] = '神秘人'
print(copy_students, students)
# 复制一个列表方法2
print(students)
copy_students = students.copy()
print(copy_students)
copy_students[0] = '神秘人'
print(copy_students, students)
# 复制一个列表方法3
print(students)
copy_students = students[:]
print(copy_students)
copy_students[0] = '神秘人'
print(copy_students, students)
slice操作
在复制列表的方法3里,我们发现了一个新的概念[:],它其实是Python列表的一种特殊操作,我们让AI给解释一下
索引可以为正数,也可以为负数,负数代表倒着数。举例说明
# 程序007.009
students = ['lu', '大白菜', '木木', '逻辑', '逆行者']
# 返回列表序号为1和2的同学列表
print(students[1:3]) # step默认1
# 返回列表序号为1和3的同学列表
print(students[1:4:2])
# 返回最后一个同学的列表
print(students[-1:]) # 猜猜students[-1]返回什么?
# 返回倒序的列表
print(students[::-1]) # start默认-1,stop默认负的 len(students)+1
print(students[-1:-(len(students)+1):-1])