-2

I have a list which contains unique strings. I want to remove a given string (if found in the list) from this list but do not want to change the indicies of all other elements in the list.

So I figure that I should just replace the given (and found) string with a None.

What's the most efficient way to do so? I thought about list comprehension, but could it be a bit overkill for just one element?

4

3 回答 3

3

这是一种简单的方法,因为列表是可变的。获得索引后,您可以分配一个新值:

list[list.index('foo')] = None
于 2013-05-30T17:43:46.617 回答
1

一些基本列表可能会有所帮助:

In [211]: L = list('abcde')

In [212]: L
Out[212]: ['a', 'b', 'c', 'd', 'e']

In [213]: i = L.index('c')

In [214]: L[i] = None

In [215]: L
Out[215]: ['a', 'b', None, 'd', 'e']

index给出第一次出现的索引,而不仅仅是分配.

于 2013-05-30T17:32:39.423 回答
0

如果您需要查找元素,您选择的任何方法都是 O(n) 或 O(log(n))(如果可用)。一旦你知道了元素的索引,替换一个元素就是一个常数时间的操作。

真正的问题是你是否真的想要一份清单。如果不需要顺序,则使用集合,在这种情况下查找和插入是 O(n)。如果你需要顺序,并且你想交换东西,然后考虑树或堆结构。

您可能错过了 python 列表是数组支持的信息,而不是链接结构。

于 2013-05-30T17:25:11.980 回答