python学习笔记03——列表
列表基础定义
中括号定义列表
列表索引从0开始
列表长度用len函数
列表最后一个元素索引值为长度减一或者负一
ex = [1, 2, 3, 4, "aa"]
print(ex)
# 列表循环输出
for each in ex:
print(each)
# 列表索引
print(ex[0])
# 列表长度
length = len(ex)
print(ex[length - 1])
print(ex[-1])
列表切片
ex[0:5:2]从列表的第0个索引值开始到第5个索引值(不包括第5个),步长是2,列表的第一个元素索引值为0
列表前后置换[::-1]
print(ex[0:3])
print(ex[3:6])
print(ex[:3])
print(ex[3:])
print(ex[0:5:2])
print(ex[::2])
print(ex[::-1])
[1, 2, 3]
[4, 5, 'aa']
[1, 2, 3]
[4, 5, 'aa']
[1, 3, 5]
[1, 3, 5]
['aa', 5, 4, 3, 2, 1]
Process finished with exit code 0
列表的增删改查
增append
列表.append()表示在末尾增加一个元素
extend方法允许直接添加可迭代对象
也可以用[len:]表示在现有列表后面继续添加
insert用于在列表任意位置insert(指定待插入的位置,插入的元素)
# 02列表的增删改查
he = ["a", "b"]
he.append("c")
print(he)
# 增加可迭代对象
he.extend(["d", "f"])
print(he)
he[len(he):] = ["g"]
print(he)
# 任意位置插入
he.insert(2,"aa")
print(he)
['a', 'b', 'c']
['a', 'b', 'c', 'd', 'f']
['a', 'b', 'c', 'd', 'f', 'g']
['a', 'b', 'aa', 'c', 'd', 'f', 'g']
Process finished with exit code 0
删remove
列表.remove(要删除的元素),若列表有多个匹配的元素只会删除第一个元素;若指定元素不存在则程序报错
pop用于删除下标对应的元素
clear用于彻底全部删除
# 列表的删除remove(要删除的元素)
re = ["a", "b", "c", "d", "e"]
re.remove("a")
print(re)
# pop清除指定位置
re.pop(3)
print(re)
# clear彻底全部删除
['b', 'c', 'd', 'e']
['b', 'c', 'd']
改
列表可变,字符串不变
可以直接指定某位置的元素为另一个
# 改
ga = ["a", "b", "c", "d", "e"]
ga[2] = "cc"
print(ga)
sort()方法对列表元素从小到大排序,reverse()对列表元素从大到小排序
查count()
count用于找到列表中包含某个元素的个数
index用于找出列表中某个元素的索引值(找到的是第一个)
list01.index(3,1,7)从索引值为1找到7查找3元素的个数
copy用于拷贝一个列表
# 列表的拷贝
num_copy = nums.copy()
print(num_copy)
num_copy2 = nums[:]
print(num_copy2)
列表的加法和乘法
列表的加法是前后连接在一起
# 列表的加法
s = [1, 2, 3]
t = [4, 5, 6]
print(s+t)
列表的嵌套
ne = [[1,2,3],[2,3,4],[3,4,5]]
matrix举证
访问嵌套列表通过双层循环
# 嵌套列表
matrix = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
for i in matrix:
for each in i:
print(each)
for i in matrix:
for each in i:
print(each, end=' ')
print()
print(matrix[0])
print(matrix[0][0])
1 2 3
2 3 4
3 4 5
[1, 2, 3]
1
Process finished with exit code 0
列表的乘法
# 列表的乘法
A = [0] * 3
print(A)
for i in range(3):
A[i] = [0] * 3
print(A)
[0, 0, 0]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
变量不是盒子
对于列表x=y,或者x=y.copy()当y中元素变的时候x中也会发生改变
深拷贝copy方法y = copy.copy(x)这样y不会改变
列表推导式
# 列表推导式
oho = [1, 2, 3, 4, 5]
oho = [i * 2 for i in oho]
print(oho)
xx = [i for i in range(10)]
print(xx)
xx2 = [i + 1 for i in range(10)]
print(xx2)
[2, 4, 6, 8, 10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
运行更加快
列表推导式[循环体表达式 for i in list]
matrix1 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
col2 = [row[1] for row in matrix1]# 第2列的元素
print(col2)
diag = [matrix1[i][i] for i in range(len(matrix))] # 对角线元素
print(diag)
# 右上角到左下角元素
可以添加if
# even if
even = [i for i in range(10) if i%2==0]
print(even)
[0, 2, 4, 6, 8]