一、列表内元素的获取
列表[0] 数字索引位置 通过此可对列表元素进行调换
>>> empty = [0,1,2,['小儿子','小西瓜'],4]
>>> a = empty[3][1]
>>> print(a)
小西瓜
二、列表的删除
1 remove()
member.remove('元素名')
2 del (del为语句,并非函数BIF)
>>> member = ['大傻子','二傻子','三傻子','四傻子']
>>> del member[2]
>>> member
['大傻子', '二傻子', '四傻子']
>>> del member
>>> member
Traceback (most recent call last):
File "
", line 1, in
member
NameError: name 'member' is not defined
3 pop() (member.pop()默认删除列表最后一个元素) (pop操作将抽取元素,有反馈值)
三、列表的分片slice (对原列表的拷贝,不影响原)
>>> member = ['大傻子','二傻子','三傻子','四傻子']
>>> member[0:2]
['大傻子', '二傻子']
>>> member
['大傻子', '二傻子', '三傻子', '四傻子']
>>> member[:3]
['大傻子', '二傻子', '三傻子']
member[:] 有两个参数start stop (stop-start=个数 stop索引不包括)
对列表进行分片拷贝
四、列表的元素插入
1 append
列表名.append('1561')
2 extend 可插入两个(用一个列表来扩展原列表)
>>> empty = []
>>> empty.extend(['大傻子','二傻子'])
>>> empty
['大傻子', '二傻子']
3 insert 插入到原列表的指定位置
>>> member = ['小小','大大']
>>> member.insert(1,'中中')
>>> member
['小小', '中中', '大大']
五、常用操作符
1 列表的比较
只比较第一个元素
2 列表相加
两列表进行拼接(类似于extend)
3 列表的乘法
>>> list1 = [123,456]
>>> list1 *3
[123, 456, 123, 456, 123, 456]
4 成员关系操作符
>>> list1 = [123,456]
>>> 123 in list1
True
>>> 1 not in list1
True
>>> list3 = [12,23,34,[1,2,3]]
>>> 1 in list3[3]
True
5 与列表相关的BIF
①count() list1.count('元素名')
②index() (索引)反馈元素所在位置 只记第一个出现的位置
共三个参数 1目标元素 2开始位置 3结束位置
>>> list5 = [5,6,1,3,9,2,3,7,3]
>>> list5.index(3)
3
>>> list5 = [5,6,1,3,9,2,3,7,3]
>>> list5.index(3,4,8)
6
③reverse() (反转)将列表元素位置反转
>>> list2 = [1,2,3,4,5,6]
>>> list2.reverse()
>>> list2
[6, 5, 4, 3, 2, 1]
④sort() 排序,默认从小到大
共三个参数 前两个默认,第三个参数为reverse(默认reverse=False)
>>> list3 = [35,48,2,0,5,4,8,12]
>>> list3.sort()
>>> list3
[0, 2, 4, 5, 8, 12, 35, 48]
>>> list3 = [35,48,2,0,5,4,8,12]
>>> list3.sort(reverse=True)
>>> list3
[48, 35, 12, 8, 5, 4, 2, 0]
⑤join()
str.join(list)
>>> a = [1,2,4,7,9]
>>> b = ','.join(a)
Traceback (most recent call last):
File "
", line 1, in
b = ','.join(a)
TypeError: sequence item 0: expected str instance, int found
>>> a = ['1','3','5','7']
>>> b = ','.join(a)
>>> b
'1,3,5,7'
>>>
6.列表推导式
(1)使用列表推导式实现嵌套列表的平铺
>>> vec = [[1,2,3],[4,5,6],[7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
(2)矩阵的转置
>>> mat = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
>>> [[row[i] for row in mat] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
>>> list(zip(*mat))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
(3)过滤元素
>>> alist = [10,-2,5.6,-9.5,33,-5]
>>> [i for i in alist if i > 0]
[10, 5.6, 33]
>>>
(4)在列表推导式中使用多个循环,实现多序列元素的任意组合,并且可以结合条件语句过滤特定元素。
>>> [(x,y) for x in [1,2,3] for y in range(2,5) if x!=y]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 2), (3, 4)]
>>>
(5)列表推导式支持文件对象迭代。
f = open('C:\xxxx.txt','r')
print([line for line in f])
f.close()
7.zip()
class zip(object)
zip(iter1 [,iter2 [...]]) --> zip object
返回[(seq1[0],seq2[0]...),(seq1[1],seq2[1]...),(..)..]形式的列表
将多个列表或元组对应位置的元素组合为元组,并返回zip对象。