Python 列表(数组)初识
Posted 云里飞
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 列表(数组)初识相关的知识,希望对你有一定的参考价值。
1 声明列表
names =["tome","jonson","black"] print(names)
2 访问列表元素
names = ["tomy","jonson","black"] print(names[0])
#访问列表最后一个元素,使用-1下标 names = ["tomy","jonson","black"] print(names[-1])
3 修改,添加,删除元素
#修改元素 names = ["tomy","jonson","black"] print(names) names[1] = "france" print(names)
names = ["tomy","jonson","black"] print(names) #在列表末尾追加元素 names.append("masa") print(names) #在列表中插入元素 names.insert(2,"jaray") print(names)
names = ["tomy","jonson","black"] print(names) #使用del删除元素 del names[1] print(names) names.insert(1,"jonson") print(names) #使用pop删除元素,pop可以弹出这个元素 #不使用参数的话,默认弹出最后一个元素 popped_name = names.pop() print(popped_name) print(names) #弹出指定位置元素 first_name = names.pop(0) print(first_name) print(names) names.append("yellow") names.append("red") names.append("jonson") print(names) #根据指定值删除元素,如果列表中有多个相同的值,remove只删除第一个符合的值 names.remove("jonson") print(names)
4 使用sort对列表进行永久性排序
names = ["red","orange","yellow","green","blue"] print(names) #正序 names.sort() print(names) #倒序 names.sort(reverse=True) print(names) #中文排序貌似不好用,网上搜索结果是需要安装中文库,以后有时间再研究,研究明白后追加到这里面 names = ["张三","李四","王五","赵六","马七"] print(names) names.sort() print(names)
5 使用sorted对列表进行临时性排序
names = ["red","orange","yellow","green","blue"] #正序 print(sorted(names)) print(names) #倒序 print(sorted(names,reverse=True)) print(names)
6 反转列表元素排列顺序
names = ["red","orange","yellow","green","blue"] #反转 names.reverse() print(names) #再次调用,又反转回来 names.reverse() print(names)
7 获取列表长度
names = ["red","orange","yellow","green","blue"] print(len(names))
以上是关于Python 列表(数组)初识的主要内容,如果未能解决你的问题,请参考以下文章