python的列表list方法大全

作为Python中最重要的数据类型,列表的应用非常广泛,说是无处不在也不为过。在python中万事万物皆为对象,所以列表也不例外,那么列表对象除了自己作为对象本身的诸多魔法方法之外,还有下面一些最常用常见的方法:

1.append( element )

在列表的最后追加元素。

>>> test = []>>> test[]>>> test.append(6)>>> test[6]>>> test.append('I love UFO!')>>> test[6, 'I love UFO!']2.clear( )

在不改变其在内存中的位置的情况下清空,即给同一个东西贴上不同的标签。

>>> raw = [1, 2, 3]>>> same = raw>>> raw[1, 2, 3]>>> same[1, 2, 3]>>> raw.clear()>>> raw[]>>> same[]有人说了,不要这么复杂吧,我直接raw=[ ] 不就行了嘛。但是还真不行,你给raw贴了个空的标签,所以raw和some的标签就不一样了,即内存地址不一样,所以值也就不一样。

>>> raw = [1, 2, 3]>>> same = raw>>> raw[1, 2, 3]>>> same[1, 2, 3]>>> raw = []>>> raw[]>>> same[1, 2, 3]>>> id(raw) == id(same) # 检测它们在内存中在不在同一个地址>>> False3.copy( )

浅拷贝。直接看例子理解,说的简单一点,就是贴标签而已。

>>> raw = [1, 2, 3]>>> same = raw>>> different = raw.copy()>>> raw[1, 2, 3]>>> same[1, 2, 3]>>> different[1, 2, 3]>>> raw.append(4)>>> raw[1, 2, 3, 4]>>> same[1, 2, 3, 4]>>> different[1, 2, 3]>>> id(raw) == id(same)True>>> id(raw) == id(different)False4.count( element )

统计列表中的某个元素出现的次数。

>>> test = [1, 1, 2, 3, 1, 2]>>> test.count(1)3>>> test.count(2)2>>> test.count(3)15.extend( )

用可迭代的序列向列表追加元素,可以理解为append( )函数的增强版。

>>> test = [1, 2, 3]>>> test[1, 2, 3]>>> test.extend([11, 22, 33])>>> test[1, 2, 3, 11, 22, 33]6.index( element )

返回某个元素在列表中【首次出现】的下标。特别注意找到第一次就不再往下找啦。

>>> test = [3, 8, 4, 2, 1]>>> test[3, 8, 4, 2, 1]>>> test.index(2)3>>> test.index(8)1>>> test.index(4)27.insert ( index , element )

在列表指定的位置上插入元素,index位置,element待插入的元素。

>>> test = [1, 1, 2, 3, 5, 8]>>> test[1, 1, 2, 3, 5, 8]>>> test.insert(3, 10)>>> test[1, 1, 2, 10, 3, 5, 8]>>> test.insert(5, 100)>>> test[1, 1, 2, 10, 3, 100, 5, 8]8.pop( )

删除列表中指定位置的元素,,默认位置为列表的结尾。

>>> test = [1, 1, 9, 3, 6, 8]>>> test[1, 1, 9, 3, 6, 8]>>> test.pop()8>>> test[1, 1, 9, 3, 6]>>> test.pop(2)9>>> test[1, 1, 3, 6]9.remove( element )

删除列表中【首次出现】的指定元素,特别注意找到首次出现的删除后就不再往下找了。

>>> test = [1, 1, 2, 3, 4, 3]>>> test[1, 1, 2, 3, 4, 3]>>> test.remove(1)>>> test[1, 2, 3, 4, 3]>>> test.remove(3)>>> test[1, 2, 4, 3]10.reverse( )

在不改变内存位置的情况下反转列表,即不不给它贴新标签,直接自身反转。

>>> test = [1, 1, 2, 3, 5, 8]>>> test[1, 1, 2, 3, 5, 8]>>> test.reverse()>>> test[8, 5, 3, 2, 1, 1]11.sort( )

给列表排序,可选参数:reverse 从大到小排;key:为列表中的每个元素按照key的计算方法计算后,按大小排序。

>>> test1 = [8, 3, -9, 2, 5, 3]>>> test1[8, 3, -9, 2, 5, 3]>>> test1.sort()>>> test1[-9, 2, 3, 3, 5, 8]>>> test1.sort(reverse = True)>>> test1[8, 5, 3, 3 2, -9]>>> test2 = ['z', 'abcde', 'cde']>>> test2['z', 'abc', 'cdeeee']>>> test2.sort() # 默认按ASCII值大小排序>>> test2['abc', 'cdeeee', 'z']>>> test2.sort(key = len) # 要求按长度排序>>> test2['z', 'abc', 'cdeeee']以上就是列表对象的常用基本方法。当然高级的还有,最重要的就是列表切片和列表推导式了,这里就不一一列举喽。

怠惰是贫穷的制造厂。

python的列表list方法大全

相关文章:

你感兴趣的文章:

标签云: