【Python】列表

前言

Python 列表
列表方法
列表操作
append
clear
copy
count
extend
index
insert
pop
remove
reverse
sort
基础操作
进阶操作
创建
访问
修改
增加
删除
遍历
成员资格
运算符
长度
最值
排序
TBD
TBD
TBD

1. 列表方法

1.1 append

list.append(obj):在列表末尾添加新的对象

list1 = [1,2,3,4]
list1.append(5)
print(list1) # [1, 2, 3, 4, 5]
list1.append([6,7])
print(list1) # [1, 2, 3, 4, 5, [6, 7]]
list1.append(8,9) # TypeError: append() takes exactly one argument (2 given)

1.2 clear

list.clear(): 清空列表,类似于del list[:]

list1 = [1,2,3,4]
list1.clear()
print(list1) # []

1.3 copy

list.copy():复制列表,类似于list[:]

list1 = [1,2,3,4]
list2 = list1.copy()
print(list2) # [1,2,3,4]

注释:list.copy()和直接通过“=”进行简单赋值的区别 [1]

  • list.copy()是浅拷贝,即拷贝父对象,不会拷贝对象的内部的子对象。通俗点讲,父对象指向不同的内存地址,因此是两个独立的对象,一方的改变不会影响另外一方;而子对象指向同一内存地址,因此是同一对象的引用,任一方的改变都会影响另外一方。
  • =:赋值引用,“=”左右对象指向同一内存地址,因此任一方的改变都会影响另外一方。

我们看一下下面的例子:

list1 = [1,[2,3],4,5]
list2 = list1 # 赋值引用
list3 = list1.copy() # 浅拷贝
list1[0] = -1 # list1在第一层的修改会影响list2,但不会影响list3
list2[2] = -4 # list2在第一层的修改也会影响list1,但不会影响list3
list3[3] = -5 # list3在第一层的修改不会影响list1和list2
list1[1][0] = -2 # list1在第二层的修改会影响list2,也会影响list3
list3[1][1] = -3 # list3在第二层的修改会影响list1,也会影响list2
print('list1:',list1) # list1: [-1, [-2, -3], -4, 5]
print('list2:',list2) # list2: [-1, [-2, -3], -4, 5]
print('list3:',list3) # list3: [1, [-2, -3], 4, -5]
print(id(list1),id(list1[0]),id(list1[1])) # 1650324110016 140722376156896 1650324109888
print(id(list2),id(list2[0]),id(list2[1])) # 1650324110016 140722376156896 1650324109888
print(id(list3),id(list3[0]),id(list3[1])) # 1650324110336 140722376156960 1650324109888

list.copy()和copy.copy(list)以及list[:]的效果一致


1.4 count

list.count(obj):统计某个元素在列表中出现的次数

list1 = [1,2,2,2,3,3,3,3]
print(list1.count(1)) # 1
print(list1.count(2)) # 3
print(list1.count(3)) # 4

# 元素值不在列表中也没关系
print(list1.count(4)) # 0

1.5 extend

list.extend(obj):通过添加可迭代对象中的元素来扩展列表,可迭代对象可以是列表、元组、集合、字典,若为字典,则仅会将键(key)作为元素依次添加至原列表的末尾

list1 = [1,2,3]
list2 = [4,5] # 列表
list3 = (6,7) # 元组
list4 = {'a':8,'b':9} # 字典
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5]
list1.extend(list3)
print(list1) # [1, 2, 3, 4, 5, 6, 7]
list1.extend(list4)
print(list1) # [1, 2, 3, 4, 5, 6, 7, 'a', 'b']

1.6 index

list.index(obj[, start[, end]]):从列表中找出某个值第一个匹配项的索引位置。如果该值不存在,则会报错

  • obj:查找的对象
  • start:可选,查找的起始位置(包含)
  • end:可选,查找的结束位置(不包含)
list1 = [1,2,3,2,1,4,3,3,4,1,1,2]
print(list1.index(1)) # 0
print(list1.index(2)) # 1
print(list1.index(3)) # 2
print(list1.index(1,4)) # 4,从位置4开始(包含)查找值1
print(list1.index(1,5,10)) # 9,查找位置5(包含)到位置10(不包含)范围内的值1
print(list1.index(5)) # ValueError: 5 is not in list

1.7 insert

list.insert(index, obj):在index之前将对象插入列表

list1 = [1,2,3]
list1.insert(0,-1)
print(list1) # [-1, 1, 2, 3]
list1.insert(1,-2)
print(list1) # [-1, -2, 1, 2, 3]
list1.insert(-3) # TypeValue: insert expected 2 arguments, got 1(需要指定index)

1.8 pop

list.pop([index=-1]):移除列表中index位置的元素(默认最后一个元素),并且返回该元素的值。如果列表为空或者index超出索引范围,则会报错

list1 = [1,2,3,4]
print(list1.pop()) # 4
print(list1.pop(0)) # 1
print(list1) # [2,3]
list1.pop(4) # IndexError: pop index out of range

1.9 remove

list.remove(obj):移除列表中某个值的第一个匹配项。如果该值不存在,则会报错

list1 = [1,2,3,2,1,4,3,3,4,1,1,2]
list1.remove(1)
print(list1) # [2, 3, 2, 1, 4, 3, 3, 4, 1, 1, 2]
list1.remove(2)
print(list1) # [3, 2, 1, 4, 3, 3, 4, 1, 1, 2]
list1.remove(5) # ValueError: list.remove(x): x not in list

1.10 reverse

list.reverse():对列表进行翻转

list1 = [1,2,3]
list1.reverse()
print(list1) # [3, 2, 1]

1.11 sort

list.sort(key=None, reverse=False):对原列表进行排序

  • key:排序键值
  • reverse:排序顺序,reverse = True 降序, reverse = False 升序(默认)
list1 = [1,3,4,2]
list1.sort()
print(list1) # [1, 2, 3, 4],升序排列
list1.sort(reverse=True)
print(list1) # [4, 3, 2, 1],降序排列

2. 列表操作

2.1 基础操作

2.1.1 创建

2.1.1.1 []创建列表

[item1,item2,…]:列表的各个元素通过逗号分隔

# 创建空列表
list1 = []

# 赋值创建列表
# 列表里面可以放入任意数据类型
list2 = [1,2,3,4]
list3 = ['a','b','c','d']
list4 = [1,'a',[2],{'c':3},(4,5)]
2.1.1.2 list()创建列表

list(iterable):返回一个列表,可选参数iterable是可迭代对象,如字符串、元组、字典、range对象等,若为字典,则会将字典的键(key)返回形成列表 [2]

# 创建空列表
list1 = list() 
print(list1) # []

# 从字符串创建列表
list2 = list('python')
print(list2) # ['p', 'y', 't', 'h', 'o', 'n']
# 从元组创建列表
list3 = list((1,2,3))
print(list3) # [1, 2, 3]
# 从字典创建列表
list4 = list({'a':1,'b':2,'c':3})
print(list4) # ['a', 'b', 'c']
# 从range对象创建列表
list5 = list(range(10))
print(list5) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 单个数值无法直接创建列表,因为单个数值不是可迭代对象
list(6) # TypeError: 'int' object is not iterable
2.1.1.3 循环创建列表
# 通过list.append()循环创建列表
list1 = []
for i in range(10):
    list1.append(i)
print(list1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 通过“+”循环创建列表
list2 = []
for i in range(10):
    list2 += [i] # list2 = list2+[i]
print(list2) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2.1.1.4 列表推导式/生成式

[表达式 for 迭代变量 in 可迭代对象 [if 条件表达式]],if条件表达式为可选参数

list1 = [x for x in range(10)]
print(list1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

list2 = [2*x+1 for x in range(10)]
print(list2) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

list3 = [x for x in range(20) if x%2==1]
print(list3) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

# 上面list3表达式是下面for循环和if条件表达式的变种
list4 = []
for x in range(20):
    if x%2==1:
        list4.append(x)
print(list4) # [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

注释:列表推导式本质上还是for循环的变种


2.1.2 访问

2.1.2.1 索引

正向索引(从左往右):索引0开始,0(第1个元素), 1(第2个元素), 2(第3个元素), …
反向索引(从右往左):索引-1开始,…,-1(倒数第1个元素),-2(倒数第2个元素),-3(倒数第3个元素)

list1 = [1,2,3,4,5,6,7,8,9,10]
print(list1[0]) # 1
print(list1[1]) # 2
print(list1[-1]) # 10
print(list1[-2]) # 9
print(list1[10]) # IndexError: list index out of range

list2 = [1,[2,3],'a']
print(list2[0]) # 1
print(list2[1]) # [2,3]
# 如果需要进一步对[2,3]进行索引
print(list2[1][0]) # 2 
print(list2[1][1]) # 3
2.1.2.2 切片

list[start: end :step]

  • start:起始索引(包含),默认为0
  • end:结束索引(不包含),默认为-1
  • step:步长(默认为1),步长为正时,从左向右取值;步长为负时,从右向左取值
  • 当步长为正时,start要比end先出现;当步长为负时,start要比end晚出现
list1 = [1,2,3,4,5,6,7,8,9,10]

# 选取从第1位开始,到最后1位结束的所有元素(不包含最后1位)
print(list1[0:9]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 选取从第1位开始,到最后1位结束的所有元素(不包含最后1位)
print(list1[0:-1]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 选取所有元素,常用来拷贝列表,等同于list.copy()
print(list1[:]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 选取所有元素
print(list1[0:]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 选取最后1位之前的所有元素(不包含最后1位)
print(list1[:-1]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 选取最后3位元素
print(list1[-3:]) # [8, 9, 10]

# 选取从第1位开始,到最后1位结束的所有元素(不包含最后1位),显示表达步长
print(list1[0:9:1]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 从第1位开始,到最后1位结束,隔1个挑选1个元素(不包含最后1位)
print(list1[0:9:2]) # [1, 3, 5, 7, 9]
print(list1[0::2]) # [1, 3, 5, 7, 9]
print(list1[:9:2]) # [1, 3, 5, 7, 9]
print(list1[::2]) # [1, 3, 5, 7, 9]

# 从最后1位开始的所有元素(相当于倒序)
print(list1[::-1]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(list1[10::-1]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(list1[-1::-1]) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

# 从最后1位开始,隔1个挑选1个元素
print(list1[::-2]) # [10, 8, 6, 4, 2]
print(list1[9::-2]) # [10, 8, 6, 4, 2]
print(list1[-1::-2]) # [10, 8, 6, 4, 2]

# 当步长为正时,start要比end先出现
print(list1[9:0:2]) # []

# 当步长为负时,start要比end晚出现
print(list1[0:9:-2]) # []

注释:
索引不可以超出列表范围,但是切片可以。

list1 = [1,2,3,4,5,6,7,8,9,10]

print(list1[10]) # IndexError: list index out of range
print(list1[:20]) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list1[20:]) # []

2.1.3 修改

2.1.3.1 元素赋值
list1 = [1,2,3,4,5]

# 元素赋值,一次只能修改列表的一个元素
list1[0] = 0
print(list1) # [0, 2, 3, 4, 5]

# 元素赋值索引不能超出列表范围
list1[5] = [6] # IndexError: list assignment index out of range
2.1.3.2 切片赋值
list1 = [1,2,3,4,5]

# 切片赋值,一次可以修改列表的多个元素
list1[:3] = [0,1,2]
print(list1) # [0, 1, 2, 4, 5]

# 切片赋值,使用与原列表片段不等长的列表进行替换
list1[3:] = [3,4,5,6]
print(list1) # [0, 1, 2, 3, 4, 5, 6]

# 切片赋值,在列表末尾插入新的元素
list1[7:] = [7,8,9]
print(list1) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 切片赋值,在列表中间插入新的元素
list1[3:3] = [1]*5
print(list1) # [0, 1, 2, 1, 1, 1, 1, 1, 3, 4, 5, 6, 7, 8, 9]

注释:
相较元素赋值,切片赋值非常强大,不仅可以一次性为多个元素赋值,而且可以使用与原列表片段不等长的列表进行替换,还可以“插入”新的元素。


2.1.4 增加

2.1.4.1 append

list.append(obj):一次只能增加一个元素,无论元素是什么形式

list1 = [1,2,3,4]

# 一次增加一个数值元素
list1.append(5)
print(list1) # [1, 2, 3, 4, 5]

# 一次增加一个列表元素
list1.append([6,7])
print(list1) # [1, 2, 3, 4, 5, [6, 7]]

# 无法一次增加两个元素
list1.append(8,9) # TypeError: append() takes exactly one argument (2 given)
2.1.4.2 extend

list.extend(obj):可一次性增加单个或多个元素,只要将单个或多个元素放入列表或元组的可迭代对象中,非常灵活

list1 = [1,2,3]
list2 = [4,5] # 列表
list3 = (6,7) # 元组
list4 = ['a','b']

# 将列表中元素一次性加入原列表中
list1.extend(list2)
print(list1) # [1, 2, 3, 4, 5]

# 将元组中元素一次性加入原列表中
list1.extend(list3)
print(list1) # [1, 2, 3, 4, 5, 6, 7]

# 如果只增加单个元素,也需要将该元素放入列表或元组这样的可迭代对象中
list1.extend([8])
print(list1) # [1, 2, 3, 4, 5, 6, 7, 8]
list1.extend(8) # TypeError: 'int' object is not iterable

# extend可加入任何类型的元素
list1.extend(list4)
print(list1) # [1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b']
list1.extend('cde')
print(list1) # [1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 'c', 'd', 'e']
2.1.4.3 连接操作“+”

连接操作“+”:和extend功能类似,支持多种可迭代对象

list1 = [1,2,3]
list2 = [4,5] # 列表
list3 = (6,7) # 元组
list4 = ['a','b']

# 将列表中元素一次性加入原列表中
list1 += list2 # 相当于list1 = list1 + list2
print(list1) # [1, 2, 3, 4, 5]

# 将元组中元素一次性加入原列表中
list1 += list3
print(list1) # [1, 2, 3, 4, 5, 6, 7]

# 如果只增加单个元素,也需要将该元素放入列表或元组这样的可迭代对象中
list1 += [8] 
print(list1) # [1, 2, 3, 4, 5, 6, 7, 8]
list1 += 8

# “+”可连接任何类型的可迭代对象
list1 += list4
print(list1) # [1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b']
list1 += 'cde'
print(list1) # [1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 'c', 'd', 'e']

2.1.4.4 切片赋值

参考2.1.3.2节。

2.1.4.5 insert

list.insert(index, obj):在index之前将对象插入列表。insert方法一次只能在指定位置增加一个元素,因此没有切片赋值灵活,但可读性更高

list1 = [1,2,3,4,5]
list2 = [1,2,3,4,5]

# insert一次只能增加一个元素
list1.insert(2,[1,1])
print(list1) # [1, 2, [1, 1], 3, 4, 5]
list1.insert(2,1,1) # TypeError: insert expected 2 arguments, got 3

# 切片赋值一次可增加多个元素,非常灵活
list2[2:2] = [1,1]
print(list2) # [1, 2, 1, 1, 3, 4, 5]

2.1.5 删除

2.1.5.1 pop

参考1.8节。

2.1.5.2 remove

参考1.9节。

2.1.5.3 clear

参考1.2节。

2.1.5.3 del

del:del配合索引或切片

list1 = [1,2,3,4,5]

del(list1[1])
print(list1) # [1, 3, 4, 5]
del(list1[2:])
print(list1) # [1, 3]
2.1.5.4 切片赋[]

元素赋[]无法实现删除

list1 = [1,2,3,4,5,6]

list1[1] = []
print(list1) # [1, [], 3, 4, 5, 6]
 
list1[1:1] = []
print(list1) # [1, [], 3, 4, 5, 6]

list1[0:2] = []
print(list1) # [3, 4, 5, 6]

list1[2:] = []
print(list1) # [3, 4]

2.1.6 遍历

2.1.6.1 索引遍历
list1 = [1,2,3,4,5,6,7,8,9,10]

# 通过索引遍历(不推荐)
for index in range(len(list1)):
    print(index) # 0 1 2 3 4 5 6 7 8 9
    print(list1[index]) # 1 2 3 4 5 6 7 8 9 10
2.1.6.2 循环体遍历
list1 = [1,2,3,4,5,6,7,8,9,10]

# 通过列表循环体遍历(Pythonic的方式,推荐)
for item in list1:
    print(item) # 1 2 3 4 5 6 7 8 9 10

2.1.7 成员资格

in:检查一个值是否在序列(不仅仅是列表)中,返回布尔运算符

list1 = [1,[2,3],'a']
print(1 in list1) # True
print(2 in list1) # False
print([2,3] in list1) # True
print('a' in list1) # True
print(a in list1) # NameError: name 'a' is not defined

2.1.8 运算符

  • “+”:列表(不光光是列表,也包括其他序列类型)的连接,具体参考2.1.4.3节
  • ”*“:列表(不光光是列表,也包括其他序列类型)的重复
list1 = [1,2,3]
list2 = [4,5]

print(list1+list2) # [1, 2, 3, 4, 5]
print(list2*3) # [4, 5, 4, 5, 4, 5]

2.1.9 长度

len(seq):内建函数len返回序列(不仅仅是列表)中所包含元素的数量

list1 = [1,2,3,4]
list2 = [1,2,[3,4]]
list3 = ['a','b','c','d']
print(len(list1)) # 4
print(len(list2)) # 3
print(len(list3)) # 4

2.1.10 最值

max(seq):内建函数max返回序列(不仅仅是列表)中最大的元素
min(seq):内建函数min返回序列(不仅仅是列表)中最小的元素

  • 当序列中元素全部为数字时,根据值的大小比较
  • 当序列中元素全部为字符串时,根据每个字符串元素每个字符的 ASCII 的大小比较 [3]
  • 当序列中元素为数字和字符串混杂时,则无法比较
# 当序列中元素全部为数字时,根据值的大小比较
list1 = [1,2,3,4]
print(max(list1)) # 4
print(min(list1)) # 1

# 当序列中元素全部为字符串时,根据每个字符串元素的第一个字符的 ASCII 的大小比较
list2 = ['I','love','you']
print(max(list2)) # you
print(min(list2)) # I
print(ord(list2[0][0])) # 73
print(ord(list2[1][0])) # 108
print(ord(list2[2][0])) # 121

# 当序列中元素为数字和字符串混杂时,则无法比较
list3 = [1,2,3,4,'I','love','you']
print(max(list3)) # TypeError: '>' not supported between instances of 'str' and 'int'
print(min(list3)) # TypeError: '>' not supported between instances of 'str' and 'int'

2.1.11 排序

2.1.11.1 sort方法

list.sort(key=None,reverse=False):对原列表进行排序

  • key:排序键值
  • reverse:排序顺序,reverse=True降序,reverse=False升序(默认)

字符串排序是按照每个字符相应的ASCII编码进行比较。

list1 = [1,3,4,2]
list2 = ['one','two','three','four']
list3 = [2,1,'b','a']

# 数值排序
list1.sort()
print(list1) # [1, 2, 3, 4],升序排列
list1.sort(reverse=True)
print(list1) # [4, 3, 2, 1],降序排列

# 字符串排序
list2.sort()
print(list2) # ['four', 'one', 'three', 'two'],具体为什么这么排序,参考下面各个字母的ASCII编码大小,也就是各个字母的先后顺序
print('f:%d'% ord('f')) # f:102
print('o:%d'% ord('o')) # o:111
print('t:%d'% ord('t')) # t:116
print('h:%d'% ord('h')) # h:104
print('w:%d'% ord('w')) # w:119

# sort不支持数值和字符串混合的排序
list3.sort() # TypeError: '<' not supported between instances of 'str' and 'int'

# 给定排序键值排序
list2.sort(key=lambda x: x[0])
print(list2) # ['four', 'one', 'two', 'three'],按照首字母顺序升序排列
list2.sort(key=lambda x: x[1], reverse=True)
print(list2) # ['two', 'four', 'one', 'three'],按照第二个字母顺序降序排列
2.1.11.2 sorted函数

sorted(iterable, key=None, reverse=False) :对可迭代对象(不仅仅是列表,而列表的sort方法只适用列表对象)进行排序

  • iterable:可迭代对象
  • key:排序键值
  • reverse:排序顺序,reverse=True降序,reverse=False升序(默认)

sorted函数和列表的sort方法在功能上几乎一样,但是更加灵活强大。而且列表的sort方法会对原列表直接做更改,而sorted函数不会,其返回修改之后的副本。

list1 = [1,3,4,2]
list2 = ['one','two','three','four']
list3 = [2,1,'b','a']

# 数值排序
print(sorted(list1)) # [1, 2, 3, 4],升序排列
print(sorted(list1,reverse=True)) # [4, 3, 2, 1],降序排列

# 字符串排序
print(sorted(list2)) # ['four', 'one', 'three', 'two'],具体为什么这么排序,参考下面各个字母的ASCII编码大小,也就是各个字母的先后顺序

# sort不支持数值和字符串混合的排序
sorted(list3) # TypeError: '<' not supported between instances of 'str' and 'int'

# 给定排序键值排序
print(sorted(list2,key=lambda x: x[0])) # ['four', 'one', 'two', 'three'],按照首字母顺序升序排列
print(sorted(list2,key=lambda x: x[1],reverse=True)) # ['two', 'four', 'one', 'three'],按照第二个字母顺序降序排列
2.1.11.3 reverse

参考1.10节。另外,list[::-1]也可实现类似的功能。

2.2 进阶操作

2.2.1 返回列表排序索引

list.sort()方法只是对原列表进行排序,但并不会返回排序列表的索引。熟悉matlab的朋友都知道,matlab中的sort排序函数不仅会返回排序之后的序列,还会返回其对应的索引序列,方便进一步的操作。

下面的方法展示了如何通过sorted函数,”逆向思维“得到排序列表的索引:

list1 = [1,3,2,5,6,9,8,7,4,10]

# 升序排序的索引值
sorted_index = sorted(range(len(list1)), key = lambda k: list1[k])
print(sorted_index) # [0, 2, 1, 8, 3, 4, 7, 6, 5, 9]

# 降序排序的索引值
sorted_index = sorted(range(len(list1)), key = lambda k: list1[k], reverse=True)
print(sorted_index) # [9, 5, 6, 7, 4, 3, 8, 1, 2, 0]

2.2.2

2.2.3

Reference

[1]: https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html
[2]: https://m.py.cn/jishu/jichu/13609.html
[3]: https://www.runoob.com/python3/python3-att-list-max.html
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值