增:
append() #添加到原有列表的最后
In [1]: names = ["老王","老李","老刘","老张"] In [2]: names.append("老赵") In [3]: names Out[3]: [‘老王‘, ‘老李‘, ‘老刘‘, ‘老张‘, ‘老赵‘]
In [6]: names = ["老王","老李","老刘","老张"] In [7]: names1 = ["悟空","八戒"] In [8]: names.append(names1) In [9]: names Out[9]: [‘老王‘, ‘老李‘, ‘老刘‘, ‘老张‘, [‘悟空‘, ‘八戒‘]] #使用append时,是把names1看做成一个对象,整体打包添加到names对象中。
insert() #在某个下标的位置添加内容
In [3]: names Out[3]: [‘老王‘, ‘老李‘, ‘老刘‘, ‘老张‘, ‘老赵‘] In [4]: names.insert(0,"小胖") In [5]: names Out[5]: [‘小胖‘, ‘老王‘, ‘老李‘, ‘老刘‘, ‘老张‘, ‘老赵‘] In [6]: names.insert(2,"葫芦娃") In [7]: names Out[7]: [‘小胖‘, ‘老王‘, ‘葫芦娃‘, ‘老李‘, ‘老刘‘, ‘老张‘, ‘老赵‘]
extend() #把两个列表组合成一个列表
In [1]: name1 = ["老王","老李"] In [2]: name2 = ["悟空","八戒"] In [3]: name1.extend(name2) In [5]: name1 Out[5]: [‘老王‘, ‘老李‘, ‘悟空‘, ‘八戒‘, ‘悟空‘, ‘八戒‘] #使用extend的时候,是将name2看作一个序列,将这个序列和name1序列合并,并放在其后面。
删:
pop() #删除最后一个元素
In [12]: name1 Out[12]: [‘老王‘, ‘老李‘, ‘悟空‘, ‘八戒‘, ‘悟空‘, ‘八戒‘] In [13]: name1.pop() Out[13]: ‘八戒‘ In [14]: name1 Out[14]: [‘老王‘, ‘老李‘, ‘悟空‘, ‘八戒‘, ‘悟空‘]
remove() #根据内容删除,只操作一次
In [15]: name1 Out[15]: [‘老王‘, ‘老李‘, ‘悟空‘, ‘八戒‘, ‘悟空‘] In [16]: name1.remove("八戒") In [17]: name1 Out[17]: [‘老王‘, ‘老李‘, ‘悟空‘, ‘悟空‘]
del #根据下标删除
In [17]: name1 Out[17]: [‘老王‘, ‘老李‘, ‘悟空‘, ‘悟空‘] In [18]: del name1[0] In [19]: name1 Out[19]: [‘老李‘, ‘悟空‘, ‘悟空‘]
改:
In [20]: name1 Out[20]: [‘老李‘, ‘悟空‘, ‘悟空‘] In [21]: name1[2] = "猪八戒" In [22]: name1 Out[22]: [‘老李‘, ‘悟空‘, ‘猪八戒‘]
查:
in / not in #判断是否存在列表里
In [23]: name1 Out[23]: [‘老李‘, ‘悟空‘, ‘猪八戒‘] In [24]: if "老李" in name1: ....: print("在里面") ....: if "小孙" not in name1: ....: print("小孙不在里面") ....: 在里面 小孙不在里面
python中获取列表元素的下标
In [1]: names = ["laowang","laoli","laozhang","laozhao"] In [2]: names.index("laoli") Out[2]: 1