Python常用列表数据结构小结
本文汇总了Python列表list一些常用的对象方法,可供初学者参考或查询,具体如下:
1.list.append(x)
把元素x添加到列表的结尾,相当于a[len(a):] =[x],代码如下:
>>> a=[1,2,3,4,5] >>> a [1, 2, 3, 4, 5] >>> a.append(-2) >>> a [1, 2, 3, 4, 5, -2]
2. list.extend(L)
将一个列表中的所有元素都添加到另一个列表中,相当于 a[len(a):] = L,代码如下:
>>> a [1, 2, 3, 4, 5, -2] >>> L=[5,9,7] >>> L [5, 9, 7] >>> a.extend(L) >>> a [1, 2, 3, 4, 5, -2, 5, 9, 7]
3. list.insert(i,x)
将元素x,插到索引号i之前,代码如下:
>>> a [1, 2, 3, 4, 5, -2, 5, 9, 7] >>> a.insert(0,-3) >>> a [-3, 1, 2, 3, 4, 5, -2, 5, 9, 7] >>> a.insert(len(a),10) >>> a [-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10]
4. list.remove(x)
删除元素x(第一次出现的),代码如下:
>>> a [-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10] >>> a.append(1) >>> a [-3, 1, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1] >>> a.remove(1) >>> a [-3, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1]
5. list.count(x)
计算元素x出现的次数,代码如下:
>>> a [-3, 2, 3, 4, 5, -2, 5, 9, 7, 10, 1] >>> a.count(3) 1
6. list.sort()
对列表元素进行排序,代码如下:
>>> a.sort() >>> a [-3, -2, 1, 2, 3, 4, 5, 5, 7, 9, 10]
7. list.reverse()
倒排列表中元素,代码如下:
>>> a [-3, -2, 1, 2, 3, 4, 5, 5, 7, 9, 10] >>> a.reverse() >>> a [10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3]
8. list.index(x)
返回表中第一个出现值为x的索引,代码如下:
>>> a [10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3] >>> a.index(9) 1
9. list.pop(i)
从列表指定位置i删除元素,并将此元素返回,若未指定位置则删除列表最后一位元素,并将此元素返回。代码如下:
>>> a [10, 9, 7, 5, 5, 4, 3, 2, 1, -2, -3] >>> a.pop(0) 10 >>> a [9, 7, 5, 5, 4, 3, 2, 1, -2, -3] >>> a.pop() -3
相关文章
PyTorch中torch.matmul()函数常见用法总结
torch.matmul()也是一种类似于矩阵相乘操作的tensor连乘操作。但是它可以利用python中的广播机制,处理一些维度不同的tensor结构进行相乘操作,这篇文章主要介绍了PyTorch中torch.matmul()函数用法总结,需要的朋友可以参考下2023-04-04
Python threading模块中lock与Rlock的使用详细讲解
python的thread模块是比较底层的模块,python的threading模块是对thread做了一些包装的,可以更加方便的被使用。这篇文章主要介绍了Python threading模块中lock与Rlock的使用2022-10-10


最新评论