如何从元组列表中删除项目? [英] How can I delete items from my list of tuples?

查看:192
本文介绍了如何从元组列表中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use a list of indices to remove items from my list of tuples:

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

我已经尝试过使用numpy了,

I have tried using numpy like so:

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

,但没有成功.

我希望我的newtupList = [(1,2),(5,6)]

I want my newtupList = [(1,2),(5,6)]

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

what am I doing wrong? I have also tried:

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

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

but this does not produce the desired result.

推荐答案

As mentioned in the docs, you need to use the axis option there, because without it being mentioned it would delete elements on a flattened version. Thus, you need to do like this -

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 删除后,就像这样-


To retain the format of list of tuples, use map after deleting, like so -

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

样品运行-

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

这篇关于如何从元组列表中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆