Index all *except* one item in python

前端 未结 9 1086
清酒与你
清酒与你 2020-11-28 23:45

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]

9条回答
  •  被撕碎了的回忆
    2020-11-29 00:17

    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]
    

    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.

    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]
    

    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.

提交回复
热议问题