从列表中删除多个元素 [英] Deleting multiple elements from a list

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

问题描述

是否可以同时从列表中删除多个元素?如果我想删除索引0和2的元素,并尝试类似del somelist[0],然后尝试del somelist[2]的方法,第二条语句实际上将删除somelist[3].

Is it possible to delete multiple elements from a list at the same time? If I want to delete elements at index 0 and 2, and try something like del somelist[0], followed by del somelist[2], the second statement will actually delete somelist[3].

我想我总是可以先删除编号较高的元素,但我希望有更好的方法.

I suppose I could always delete the higher numbered elements first but I'm hoping there is a better way.

推荐答案

可能不是解决此问题的最佳方法:

Probably not the best solution for this problem:

indices = 0, 2
somelist = [i for j, i in enumerate(somelist) if j not in indices]

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

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