数据类型--列表
#每次的总结只针对我个人学习过程中的通俗易懂的理解,以及项目中常用的场景知识介绍,更深入的研究还需向大咖们学习。
本章是对python中列表知识的整理总结。
1、列表的特性
# 关键字 list 标识[],使用最频繁的数据类型。
# 列表中的元素可以是任意类型的数据
# 有序数据可变:有索引值;列表内的数据可以修改、替换、删除。
1)空列表
w=[] print(w) 返回空值
2)列表内只有一个元素的话,不需要后面加逗号(与元组的区别);多个元素的话,必须用逗号隔开
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
2、列表的操作
1)取值:同样通过索引值,列表名[索引值] ---嵌套取值
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
# 取 hello中的o
print(w[-1][-2][-1][-1])
2)切片:同字符串 列表名[start:end:step]
3)判断元素 in not in 成员运算符
print('songsong' in w) 返回:True
3、列表常见方法
1)列表名.append()函数:默认追加元素到列表的末尾,每次只能添加一个元素
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
w.append('兜兜')
w.append('doudou')
print(w)
返回:[1, 0.02, False, 'songsong', (1, 2, 3), [1, True, ['hello'], (4, 5)], '兜兜','doudou']
2)列表名.insert()函数:加元素到列表的指定位置,原有位置的元素往后挪一位
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
# 索引值为3即位置4的地方插入kk
w.insert(3,'kk')
print(w)
返回:[1, 0.02, False, 'kk', 'songsong', (1, 2, 3), [1, True, ['hello'], (4, 5)]]
3)列表名.extend()函数:拓展列表的操作,将extend中的列表元素合并到原有列表中
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
w.extend([1,2,3,4])
print(w) 返回:[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)],1,2,3,4]
4)两个列表相加:拓展列表的操作
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
q=[2,2,2]
w=w+q
print(w) 返回:[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)],2,2,2]
4)修改列表的元素值=:将某个位置的值进行重新赋值
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
# 将列表中最后一个元素修改
w[-1]='热爱学习'
print(w)
返回:[1,0.02,False,'songsong',(1,2,3),'热爱学习']
5)列表名.pop()函数:删除列表最后位置的一个元素
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
w.pop()
print(w) 返回:[1,0.02,False,'songsong',(1,2,3)]
6)列表名.pop(索引值)函数 :删除列表指定位置的元素
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
w.pop(1)
print(w) 返回:[1,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
7)列表名.sort()函数:自动排序
c=[7,6,8,1]
c.sort()
print(c) 返回:[1, 6, 7, 8]
8)列表名.reverse()函数:列表中的元素倒置
c=[7,6,8,1]
c.reverse()
print(c) 返回:[1, 8, 6, 7]
9)列表名.clear()函数:清空列表中的所有元素
c=[7,6,8,1]
c.clear()
print(c) 返回:[]
练习:
w=[1,0.02,False,'songsong',(1,2,3),[1,True,['hello'],(4,5)]]
1、添加java这个字符串到hello这个字符串所在列表中
w[-1][2].append('java')
print(w)

浙公网安备 33010602011771号