python - 如何从元组列表中删除项目?

标签 python numpy

我想使用索引列表从元组列表中删除项目:

mytupList = [(1,2),(2,3),(5,6),(8,9)]
indxList = [1,3]

我尝试过像这样使用 numpy:

newtupList = numpy.delete(mytupList,indxList).tolist()

但它没有起作用。

我想要我的 newtupList = [(1,2),(5,6)]

我做错了什么?我也尝试过:

a = np.array(mytupList) 
newtup = np.delete((a),indxList)

但这不会产生预期的结果。

最佳答案

docs 中所述,您需要在那里使用 axis 选项,因为如果不提及它,它将删除扁平版本上的元素。因此,你需要这样做 -

np.delete(mytupList,indxList,axis=0).tolist()

示例运行 -

In [21]: mytupList
Out[21]: [(1, 2), (2, 3), (5, 6), (8, 9)]

In [22]: indxList
Out[22]: [1, 3]

In [23]: np.delete(mytupList,indxList).tolist() # Flattens and deletes
Out[23]: [1, 2, 5, 6, 8, 9]

In [24]: np.delete(mytupList,indxList,axis=0).tolist() # Correct usage
Out[24]: [[1, 2], [5, 6]]
<小时/>

要保留元组列表的格式,请使用 map删除后,就像这样 -

map(tuple,np.delete(mytupList,indxList,axis=0))

示例运行 -

In [16]: map(tuple,np.delete(mytupList,indxList,axis=0))
Out[16]: [(1, 2), (5, 6)]

关于python - 如何从元组列表中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34788853/

相关文章:

python - 高效查找具有割断的邻居并返回索引

python - 仅提取属于特定 kmeans 标签的样本

python - 处理 NaN 进行距离计算时出现问题?

python - Pandas 数据框获取扩展/滚动值计数

python - 与 Scikit-Learn 的 Logistic 回归相比,Tensorflow 的性能要差得多

javascript - 如何在 Selenium Python 中处理模态框或弹出框

python - 根据条件有效反转列表中的 float

python - python中特定几何图形的二维等值线图

python - 无法使用 print(var,end ='' ) 逐行输出

python - 启动包含管道命令的子进程时找不到文件错误