在Python中按索引从列表中删除元素的简便方法 [英] Concise way to remove elements from list by index in Python

查看:408
本文介绍了在Python中按索引从列表中删除元素的简便方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符列表和索引列表

I have a list of characters and list of indexes

myList = ['a','b','c','d']
toRemove = [0,2]

我想一次完成操作

myList = ['b','d']

我可以这样做,但是有办法更快吗?

I could do this but is there is a way to do it faster?

toRemove.reverse()
for i in toRemove:
    myList.pop(i)

推荐答案

如果愿意,可以使用numpy.

import numpy as np

myList = ['a','b','c','d']
toRemove = [0,2]

new_list = np.delete(myList, toRemove)

结果:

>>> new_list
array(['b', 'd'], 
      dtype='|S1')

请注意,new_listnumpy array.

这篇关于在Python中按索引从列表中删除元素的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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