目录
4.1 列表介绍
序列是 Python 中最基本的数据结构。
序列中的每个值都有对应的位置值,称之为索引,第一个索引是 0,第二个索引是 1,依此类推。
Python 有 6 个序列的内置类型,但最常见的是列表和元组。
列表都可以进行的操作包括索引,切片,加,乘,检查成员。
此外,Python 已经内置确定序列的长度以及确定最大和最小的元素的方法。
列表是最常用的 Python 数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型
4.2 列表创建
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:
list1 = ['Google', 'Baidu', 1977, 2022,2.2]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
可以用type函数查看一个列表的数据类型,可以看到list1列表的类型为list
print(type(list1))
#<class 'list'>
4.3 列表删除
列表中元素的删除,可以根据元素值删除,也可按索引删除。
remove方法是根据元素删除,指定要删除的元素的值,一次只能删除一个值,如现在删除list1列表中的2.2数值。
list1.remove(2.2)
print(list1)
#['Google', 'Baidu', 1977, 2022]
pop方法是按照索引删除,即指定要删除字符所在的位置,如删除list1列表中2022这个值,已知2022是该列表中的最后一位
list1.pop(-1)
print(list1)
#['Google', 'Baidu', 1977]
del函数,永久删除,效果一样,不同的是一个是python中的函数,一个是面向对象的方法。
del list1[1]
print(list1)
#['Google', 1977]
4.4 列表更新
你可以对列表的数据项进行修改或更新,你也可以使用 append() 方法来添加列表项
list = ['Google', 'Runoob', 1997, 2000]
print ("第三个元素为 : ", list[2])
list[2] = 2001
print ("更新后的第三个元素为 : ", list[2])
list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1)
4.5 列表访问
以list4=['red', 'green', 'blue', 'yellow', 'white', 'black']讲解。
与字符串的索引一样,列表索引从 0 开始,第二个索引是 1,依此类推。
通过索引列表可以进行截取、组合等操作。
list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[0] )#red
print( list[1] )#green
print( list[2] )#blue
索引也可以从尾部开始,最后一个元素的索引为 -1,往前一位为 -2,以此类推。
list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
print( list[-1] )#black
print( list[-2] )#white
print( list[-3] )#yellow
使用下标索引来访问列表中的值,同样你也可以使用方括号 [] 的形式截取字符,如下所示:
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(nums[0:4])
#[10, 20, 30, 40]
使用负数索引值截取:
list = ['Google', 'Runoob', "Zhihu", "Taobao", "Wiki"]
# 读取第二位
print ("list[1]: ", list[1])
# 从第二位开始(包含)截取到倒数第二位(不包含)
print ("list[1:-2]: ", list[1:-2])
# list[1]: Runoob
# list[1:-2]: ['Runoob', 'Zhihu']
4.6 列表遍历
方便有可以有效率的输出列表每一个数据,可以用循环来实现。
使用for循环
list=[1,2,3,4,5]
for name in list:
print(name)
##运行结果如下
使用while循环
list=[1,2,3,4,5]
len=len(list)
i=0
while i<len:
print(list[i])
i+=1
使用 enumerate() 函数遍历
numbers = [1, 2, 3]
for i, n in enumerate(numbers):
print(i, n)
'''
0 1
1 2
2 3
'''
使用 iter() 函数遍历
numbers = [1, 2, 3]
for n in iter(numbers):
print(n)
使用range() 和 len() 函数进行遍历
numbers = [1, 2, 3]
for i in range(len(numbers)):
print(i, numbers[i])
使用递归遍历
numbers = [1, 2, 3]
def recursion(list, index):
if index == len(list):
return
else:
print(list[index])
recursion(numbers, index + 1)
recursion(numbers, 0)
4.7 列表嵌套
列表支持嵌套。列表嵌套指的是一个列表的元素又是一个列表。
#列表支持嵌套
school_names = [['北京大学','清华大学'],
['南开大学','天津大学','师范大学'],
['山东大学','武汉大学']]
for temp in school_names:
print(temp)
'''
['北京大学', '清华大学']
['南开大学', '天津大学', '师范大学']
['山东大学', '武汉大学']
'''
1、分配问题
已知某学校有3个办公室和8名教师,请编写一个程序,完成教师和办公室的随机分配。
要完成以上要求,可以按照一下步骤来设计程序:
- 定义一个包含3个空列表的列表offices,该列表中每个空列表代表空办公室,下标代表办公室的编号;
- 定义一个列表names,该列表中储存8位教师的姓名;
- 遍历names取出每位教师的姓名,之后再随机选取一个代表办公室的空列表,将教师姓名添加到里面;
- 输出每个办公室列表的信息。
接下来,按照上述要求编写程序实现案例,代码如下:
import random
#定义一个列表用来保存3个办公室
offices = [[], [], []]
#定义一个列表用来储存8位老师的名字
names = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
for name in names:
index = random.randint(0, 2)
offices[index].append(name)
i = 1
for temp in offices:
print('办公室%d的人数为:%d' % (i, len(temp)))
i +=1
for name in temp:
print("%s" % name, end='')
print("-" * 20)
'''
办公室1的人数为:2
BC--------------------
办公室2的人数为:4
DFGH--------------------
办公室3的人数为:2
AE--------------------'''
2、展开问题
对于列表形如 list = [[1, 2], [3, 4, 5], [6, 7], [8], [9]] 转化成列表 list_2 = [1, 2, 3, 4, 5, 6, 7, 8, 9] 的问题。
# 普通方法
list_1 = [[1, 2], [3, 4, 5], [6, 7], [8], [9]]
list_2 = []
for _ in list_1:
list_2 += _
print(list_2)
# 列表推导
list_1 = [[1, 2], [3, 4, 5], [6, 7], [8], [9]]
list_2 = [i for k in list_1 for i in k]
print(list_2)
# 使用sum
list_1 = [[1, 2], [3, 4, 5], [6, 7], [8], [9]]
list_2 = sum(list_1, [])
print(list_2)
'''
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
'''
对于复杂一些的,如:list =[1,[2],[[3]],[[4,[5],6]],7,8,[9]],上面的方法就不好使了。得换个方法了,这里使用递归的方法解决。
def flat(nums):
res = []
for i in nums:
if isinstance(i, list):
res.extend(flat(i))
else:
res.append(i)
return res
4.8 列表操作
列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。
如下所示:
Python 表达式 | 结果 | 描述 |
---|---|---|
len([1, 2, 3]) | 3 | 长度 |
[1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | 组合 |
['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | 重复 |
3 in [1, 2, 3] | True | 元素是否存在于列表中 |
for x in [1, 2, 3]: print(x, end=" ") | 1 2 3 | 迭代 |
4.9 列表函数
Python包含以下函数:
序号 | 函数 |
---|---|
1 | len(list) 列表元素个数 |
2 | max(list) 返回列表元素最大值 |
3 | min(list) 返回列表元素最小值 |
4 | list(seq) 将元组转换为列表 |
Python包含以下方法:
序号 | 方法 |
---|---|
1 | list.append(obj) 在列表末尾添加新的对象 |
2 | list.count(obj) 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) 将对象插入列表 |
6 | list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) 移除列表中某个值的第一个匹配项 |
8 | list.reverse() 反向列表中元素 |
9 | list.sort( key=None, reverse=False) 对原列表进行排序 |
10 | list.clear() 清空列表 |
11 | list.copy() 复制列表 |