python3 列表函数

以下讲解几个常用操作列表的函数

Python中列表是可变的,这是它区别于字符串和元组的最重要的特点,一句话概括即:列表可以修改,而字符串和元组不能。

以下是 Python 中列表的方法

列表函数 含义
list.append(x) 把一个元素添加到列表的结尾,相当于 a[len(a):] = [x]。
list.extend(L) 通过添加指定列表的所有元素来扩充列表,相当于 a[len(a):] = L。
list.insert(i, x) 在指定位置插入一个元素。第一个参数是准备插入到其前面的那个元素的索引。
list.remove(x) 删除列表中值为 x 的第一个元素。如果没有这样的元素,就会返回一个错误。
list.pop([i]) 从列表的指定位置移除元素,并将其返回。如果没有指定索引,a.pop()返回最后一个元素。元素随即从列表中被移除。
list.clear() 移除列表中的所有项,等于del a[:]。
list.index(x) 返回列表中第一个值为 x 的元素的索引。如果没有匹配的元素就会返回一个错误。
list.count(x) 返回 x 在列表中出现的次数。
list.sort() 对列表中的元素进行排序。
list.reverse() 倒排列表中的元素。
list.copy() 返回列表的浅复制,等于a[:]。

根据列表中函数的用法,以下举例说明

list.append()

>>> dpc = [1,2,3]
>>> dpc.append(4)
>>> print (dpc)
[1, 2, 3, 4]

list.extend()

>>> dpc = [1,2,3]
>>> a = ['a','b','c']
>>> dpc.extend(a)
>>> print (dpc)
[1, 2, 3, 'a', 'b', 'c']

list.insert()

>>> dpc = [1,2,3]
>>> dpc.insert(0,0)
>>> print (dpc)
[0, 1, 2, 3]

list.remove()

>>> dpc = [1,2,3]
>>> dpc.remove(1)
>>> print (dpc)
[2, 3]

#如果删除列表中不纯在的值会报错

>>> dpc.remove(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

list.pop()

>>> dpc = [1,2,3]
>>> dpc.pop(1)
2
>>> print (dpc)
[1, 3]

#如果不指定列表中的索引值,会返回列表最后一个元素

>>> dpc.pop()
3
>>> print (dpc)
[1]

list.clear()

>>> dpc = [1,2,3]
>>> dpc.clear()
>>> print (dpc)
[]

list.index()

>>> dpc = [1,2,3]
>>> dpc.index(2)
1

#如果没有匹配的元素就会返回一个错误

>>> dpc.index(4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 4 is not in list

list.count()

>>> dpc = [1,1,2,2,2]
>>> print ('数值1的个数 {0}\n数值2的个数 {1}'.format(dpc.count(1),dpc.count(2)))
数值1的个数 2
数值2的个数 3
 

list.sort()

>>> dpc = [3,2,1]
>>> dpc.sort()
>>> print (dpc)
[1, 2, 3]

#如果列表中的存在字符串类型就会报错

>>> dpc = ['3',2,1]
>>> dpc.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'

list.reverse()

>>> dpc = [1,2,3]
>>> dpc.reverse()
>>> print (dpc)
[3, 2, 1]

#list.reverse同样也不支持字符中排序,如果有字符串会返回错误

list.copy()

>>> dpc = [1,2,3]
>>> dpc.copy()
[1, 2, 3]

猜你喜欢

转载自blog.csdn.net/qq_31755183/article/details/85597757