索引所有*除了* python中的一个项目 [英] Index all *except* one item in python
问题描述
是否有一种简单的方法可以索引特定索引的除之外的所有元素(或数组,或其他)?例如,
Is there a simple way to index all elements of a list (or array, or whatever) except for a particular index? E.g.,
-
mylist [3]
将返回该项目的位置3
mylist[3]
will return the item in position 3
milist [~3]
将返回除3之外的整个列表
milist[~3]
will return the whole list except for 3
推荐答案
对于列表,您可以使用列表补偿。例如,要使 b
复制 a
而不使用第3个元素:
For a list, you could use a list comp. For example, to make b
a copy of a
without the 3rd element:
a = range(10)[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
b = [x for i,x in enumerate(a) if i!=3] # [9, 8, 7, 5, 4, 3, 2, 1, 0]
这是非常通用的,可以用于所有迭代,包括numpy数组。如果用()
替换 []
, b
将是一个迭代器而不是一个列表。
This is very general, and can be used with all iterables, including numpy arrays. If you replace []
with ()
, b
will be an iterator instead of a list.
或者你可以使用 pop
就地执行此操作:
Or you could do this in-place with pop
:
a = range(10)[::-1] # a = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
a.pop(3) # a = [9, 8, 7, 5, 4, 3, 2, 1, 0]
在 numpy 中,您可以使用布尔索引来执行此操作:
In numpy you could do this with a boolean indexing:
a = np.arange(9, -1, -1) # a = array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
b = a[np.arange(len(a))!=3] # b = array([9, 8, 7, 5, 4, 3, 2, 1, 0])
一般来说,它比上面列出的列表理解要快得多。
which will, in general, be much faster than the list comprehension listed above.
这篇关于索引所有*除了* python中的一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!