如何同时从列表中删除多个索引? [英] How to remove multiple indexes from a list at the same time?

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

问题描述

说我在这里有这个清单:

Say I have this list here:

list = [a, b, c, d, e, f, g]

我如何同时删除2、3、4 和 5 这样的索引?

How would I delete say indexes 2, 3, 4, and 5 at the same time?

pop不接受多个值.我还能怎么做?

pop doesn't accept multiple values. How else do I do this?

推荐答案

您需要循环执行此操作,没有内置操作可以一次删除多个索引.

You need to do this in a loop, there is no built-in operation to remove a number of indexes at once.

您的示例实际上是一个连续的索引序列,因此您可以执行以下操作:

Your example is actually a contiguous sequence of indexes, so you can do this:

del my_list[2:6]

删除从 2 开始到 6 之前结束的切片.

which removes the slice starting at 2 and ending just before 6.

目前尚不清楚您是否通常需要删除任意的索引集合,或者它是否始终是连续的序列.

It isn't clear from your question whether in general you need to remove an arbitrary collection of indexes, or if it will always be a contiguous sequence.

如果您具有任意索引集合,则:

If you have an arbitrary collection of indexes, then:

indexes = [2, 3, 5]
for index in sorted(indexes, reverse=True):
    del my_list[index]

请注意,您需要以相反的顺序删除它们,以免丢失后续的索引.

Note that you need to delete them in reverse order so that you don't throw off the subsequent indexes.

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

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