点击
“寻梦暖屋”一键
关注,感谢支持!
好久没用python了,之前学的已经忘的一干二净,今天就来复习下列表。
List(列表) 是 Python 中使用最频繁的数据类型。
列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(即嵌套)。
列表用 [ ] 标识,是 python 最通用的复合数据类型。
列表中值的切割也可以用到变量 [头下标:尾下标] ,就可以截取相应的列表,从左到右索引默认 0 开始,从右到左索引默认 -1 开始,下标可以为空表示取到头或尾。
图片来源于菜鸟教程
通过索引可以取值:
test_1 = [1,2,'幸福',[3,4,5],'abc',]print(test_1[2])幸福print(test_1[4])abc
通过切片可以取值:
test_2 = [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']print(test_2[2:3])['幸福']print(test_2[4:5])['abc']
可以for循环,while循环:
test_3 = [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']for temp in test_3: if temp == '幸福' or temp =='abc': print(temp) 幸福abc
可以通过索引的方式修改和删除:
修改:test_4 = [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']test_4[2]= '小确幸'print(test_4)[1, 2, '小确幸', [3, 4, 5, 6], 'abc', 7, 8, '快乐']删除:test_5 = [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']del test_5[2]print(test_5)[1, 2, [3, 4, 5, 6], 'abc', 7, 8, '快乐']
可以通过切片的方式修改和删除:
修改:test_6 = [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']test_6[2:5]= ['小确幸','美好','健康']print(test_6)[1, 2, '小确幸', '美好', '健康', 7, 8, '快乐']删除:test_7= [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']del test_7[2:5]print(test_7)[1, 2, 7, 8, '快乐']
支持in操作:
test_8= [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']temp01 = '幸福' in test_8print(temp01)True
test_9= [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']temp02 = '悲伤' in test_9print(temp02)False
在列表中以逗号分割的才为一个元素:
test_10= [1,2,'幸福',[3,4,5,6],'abc',7,8,'快乐']temp03 = 5 in test_10[3]print(temp03True
字符串转换列表:
test_11=list('beautiful')print(test_11)['b', 'e', 'a', 'u', 't', 'i', 'f', 'u', 'l']
列表转换成字符串(只有字符串): 直接使用“”.join方法
test_12=['haohao','学习''xiaoma','哥']temp03 = ''.join(test_12)print(temp03)haohao学习xiaoma哥
列表转换成字符串(既有数字又有字符串): 需要写个for循环
test_13=[5,20,1314,'xiaoma','哥']temp02 = ''for i in test_13: temp02 += str(i)print(temp02)5201314xiaoma哥
今天的复习就到这里了,明天继续。
客官!麻烦点下在看呗