从Python 2.7中的数字列表中删除一组索引的最有效方法是什么? [英] What is the most efficient way to remove a group of indices from a list of numbers in Python 2.7?

查看:131
本文介绍了从Python 2.7中的数字列表中删除一组索引的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想知道如何使用Python 2.7,最有效地获取用于表示这样的索引的值列表:(但长度最多为250,000 +)

So I was wondering how I can, using Python 2.7, most efficiently take a list of values used to represent indices like this: (but with a length of up to 250,000+)

indices = [2, 4, 5]

并从更大的列表中删除索引列表,如下所示:(3,000,000多项)

and remove that list of indices from a larger list like this: (3,000,000+ items)

numbers = [2, 6, 12, 20, 24, 40, 42, 51]

得到这样的结果:

[2, 6, 20, 42, 51]

我正在寻找一种比其他任何方式更有效的解决方案。我知道有很多方法可以做到这一点,但这不是我的问题。效率是。此外,此操作必须多次完成,列表将以指数方式变小。我没有一个等式来表示它们随着时间的推移会变小多少。

I'm looking for an efficient solution more than anything else. I know there are many ways to do this, however that's not my problem. Efficiency is. Also, this operation will have to be done many times and the lists will both get exponentially smaller. I do not have an equation to represent how much smaller they will get over time.

编辑:

数字必须在整个时间内按列表排序,或者在删除索引后返回排序。名为indices的列表可以排序也可以不排序。它甚至不必在列表中。

Numbers must remain sorted in a list the entire time or return to being sorted after the indices have been removed. The list called indices can either be sorted or not sorted. It doesn't even have to be in a list.

推荐答案

我怀疑在索引之间取整个切片可能是比列表理解更快

I have a suspicion that taking whole slices between the indices might be faster than the list comprehension

def remove_indices(numbers, indices):
    result = []
    i=0
    for j in sorted(indices):
        result += numbers[i:j]
        i = j+1
    result += numbers[i:]
    return result

这篇关于从Python 2.7中的数字列表中删除一组索引的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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