我想使用索引列表从元组列表中删除项目:
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/