1.作用
按位置存储多个值
2.定义
l = [1, 2, 'a']
print(l, type(l))
[1, 2, 'a'] <class 'list'>
3.类型转换
能被for 循环的类型都可以被list进行类型转换
# 字符串
res = list('hello')
print(res)
['h', 'e', 'l', 'l', 'o']
# 字典
l = list({'k1':111,'k2':222,'k3':333})
print(l)
['k1', 'k2', 'k3']
4.内置方法
优先掌握的操作:
4.1 按照索引取值;正向取、反向取、可以取也可以改
# 正向取
l = ['aa',2,'cc']
print(l[0])
aa
# 反向取
print(l[-1])
cc
# 改操作
l[0] = 333
print(l)
[333, 2, 'cc']
注:无论是取还是改,如果索引不存在则报错
l = ['aa',2,'cc']
l[3] = 444
print(l)
l[3] = 444
IndexError: list assignment index out of range
4.2 切片(顾头不顾尾)、步长
l = ['a', 2, 'c', 4, 5]
print(l[0:3])
['a', 2, 'c']
print(l[0:3:2])
['a', 'c']
print(l[::-1])
[5, 4, 'c', 2, 'a']
补充:切片等同于浅拷贝行为
l = [111, 'a', 'b', 'c', 'd', [1, 2, 3]]
new_l = l[:] # 切片等同于拷贝行为,而且相当于浅copy
print(id(l))
4456770560
print(id(new_l))
4456770304
l[-1][0] = 1111111
print(l)
[111, 'a', 'b', 'c', 'd', [1111111, 2, 3]]
print(new_l)
[111, 'a', 'b', 'c', 'd', [1111111, 2, 3]]
4.3 长度
l = ['aa',2,'cc']
print(len(l))
3
4.4 成员运算
l = ['aa',2,'cc']
print('bb' in l)
False
print('aa' not in l)
False
4.5 往列表里添加值
1)追加
l = ['aa',2,'cc']
l.append('ddd')
print(l)
['aa', 2, 'cc', 'ddd'] # 追加的末尾
2)插入
l = ['aa',2,'cc']
l.insert(1,'bbb') # 根据索引插入值,添加的对应索引的前面
print(l)
['aa', 'bbb', 2, 'cc']
3)extend 添加值
把一个列表添加到另一个列表里
l = ['aa',2,'cc']
res = [1,2,3]
l.extend(res)
print(l)
['aa', 2, 'cc', 1, 2, 3]
4.6 删除
1)del
l = ['aa',2,'cc']
del l[0]
print(l)
[2, 'cc']
2)pop (有返回值)
l = ['aa',2,'cc']
l.pop(0) # 根据索引删除
print(l)
[2, 'cc']
# 返回值
res = l.pop(0) # 根据索引删除
print(res)
aa
3)remove (根据元素删除,返回None
l = ['aa',2,'cc']
l.remove(2)
print(l)
['aa', 'cc']
# 返回None
res = l.remove(2)
print(res)
None
4.9 循环
l = ['aa',2,'cc']
for x in l:
print(x)
aa
2
cc
5.需要掌握的操作
5.1 count
检索元素在列表中出现的次数
l = ['aa',2,'cc','aa']
print(l.count('aa'))
2
5.2 index
检索元素在列表中第一次出现的索引
l = ['aa',2,'cc','aa']
print(l.index(2))
1
# 找不到则报错
l = ['aa',2,'cc','aa']
print(l.index(2222))
print(l.index(2222))
ValueError: 2222 is not in list
5.3 clear
清空列表
l = ['aa',2,'cc','aa']
l.clear()
print(l)
[]
5.4 reverse
将列表反转
l = ['aa',2,'cc','aa']
l.reverse()
print(l)
['aa', 'cc', 2, 'aa']
5.5 sort
排序 (列表内的元素必须是同一类型才可排序)
l = [31, 2, 4, 7]
l.sort()
print(l)
[2, 4, 7, 31]
默认从小到大,成为升序
sort跟reverse连用,可将升序转为降序
l = [31, 2, 4, 7]
l.sort(reverse=True)
print(l)
[31, 7, 4, 2]
补充:字符串之间也可比大小,按照对应位置的值依次比较
字符串的大小是按照ASCI码表的先后顺序加以区别,表中排在后面的字符大于前面的
print('a'>'b')
print('abz'>'abcdefg')
False
True
列表也可以比大小,原理同字符串一样,但是对应位置的元素必须是同种类型
l1=[1,'abc','zaa']
l2=[1,'abc','zb']
print(l1 < l2)
True
5.6 队列与堆栈
1)队列 FIFO(first in first out 先进先出)
l = []
# 入队操作
l.append('first')
l.append('second')
l.append('third')
print(l)
['first', 'second', 'third']
# 出队操作
print(l.pop(0))
first
print(l.pop(0))
second
print(l.pop(0))
third
2)堆栈 LIFO (list in first out 后进先出 )
l=[]
# 入栈操作
l.append('first')
l.append('second')
l.append('third')
print(l)
['first', 'second', 'third']
# 出队操作
print(l.pop())
third
print(l.pop())
second
print(l.pop())
first