使用Python从索引列表中删除多个元素

6
我有一个数值列表和一个索引列表,需要移除索引指向的元素。
这是我的解决方案,但我不喜欢它的实现方式,因为它需要导入包,在值包含maxint时无法工作,并且需要多次迭代值。
def remove_abnormalities(values, indices):
    v = list(values)
    for i in indices:
        v[i] = sys.maxint
    return filter(lambda i: i != sys.maxint, v)

有更好的解决方案吗?
2个回答

9
这应该有效:

def remove_abnormalities(values, indices):
    return [val for i, val in enumerate(values) if i not in indices]

此外,如果索引数量较大,您可以在过滤之前将indices转换为集合(set),以获得更好的性能。

[values[i] for i in range(len(values)) if i not in indices][val for i, val in enumerate(values) if i not in indices] 更好,还是反过来? - Saravanabalagi Ramachandran
@ZekeDran 后者被认为更符合Python风格。 - orlp

1
这里有一个仅使用内置列表方法的版本。它相当幼稚,因此可能存在更快的解决方案,但不需要额外的包等,这可能是您需要的。
def remove_abnormalities(values, indices):
    list = []
    for i in range(len(values)):
        if i not in indices:
           list.append(values[i])
    return list

print(remove_abnormalities(["A","B","C","D","E","F","G","H"],[1,3,5]))
#output is ['A', 'C', 'E', 'G', 'H']

如果有其他Python大师想要建议修改/优化,请随意。
编辑
我尝试在花哨的和我天真的实现中使用timeit函数,它们并不具有决定性,但其中一个似乎并不比另一个快。虽然这是在解释器中手动完成的,但无法获得脚本工作。就性能而言,它们之间的差异不大。但如果有人能证明我错了,我也不介意!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接