Index all *except* one item in python

前端 未结 9 873
清酒与你
清酒与你 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-28 23:51

    The simplest way I found was:

    mylist[:x] + mylist[x+1:]
    

    that will produce your mylist without the element at index x.

    Example

    mylist = [0, 1, 2, 3, 4, 5]
    x = 3
    mylist[:x] + mylist[x+1:]
    

    Result produced

    mylist = [0, 1, 2, 4, 5]
    
    0 讨论(0)
  • 2020-11-28 23:52
    >>> l = range(1,10)
    >>> l
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> l[:2] 
    [1, 2]
    >>> l[3:]
    [4, 5, 6, 7, 8, 9]
    >>> l[:2] + l[3:]
    [1, 2, 4, 5, 6, 7, 8, 9]
    >>> 
    

    See also

    Explain Python's slice notation

    0 讨论(0)
  • 2020-11-28 23:56

    Use np.delete ! It does not actually delete anything inplace

    Example:

    import numpy as np
    a = np.array([[1,4],[5,7],[3,1]])                                       
    
    # a: array([[1, 4],
    #           [5, 7],
    #           [3, 1]])
    
    ind = np.array([0,1])                                                   
    
    # ind: array([0, 1])
    
    # a[ind]: array([[1, 4],
    #                [5, 7]])
    
    all_except_index = np.delete(a, ind, axis=0)                                              
    # all_except_index: array([[3, 1]])
    
    # a: (still the same): array([[1, 4],
    #                             [5, 7],
    #                             [3, 1]])
    
    0 讨论(0)
  • 2020-11-28 23:58

    If you want to cut out the last or the first do this:

    list = ["This", "is", "a", "list"]
    listnolast = list[:-1]
    listnofirst = list[1:]
    
    

    If you change 1 to 2 the first 2 characters will be removed not the second. Hope this still helps!

    0 讨论(0)
  • 2020-11-29 00:00

    If you don't know the index beforehand here is a function that will work

    def reverse_index(l, index):
        try:
            l.pop(index)
            return l
        except IndexError:
            return False
    
    0 讨论(0)
  • 2020-11-29 00:03

    If you are using numpy, the closest, I can think of is using a mask

    >>> import numpy as np
    >>> arr = np.arange(1,10)
    >>> mask = np.ones(arr.shape,dtype=bool)
    >>> mask[5]=0
    >>> arr[mask]
    array([1, 2, 3, 4, 5, 7, 8, 9])
    

    Something similar can be achieved using itertools without numpy

    >>> from itertools import compress
    >>> arr = range(1,10)
    >>> mask = [1]*len(arr)
    >>> mask[5]=0
    >>> list(compress(arr,mask))
    [1, 2, 3, 4, 5, 7, 8, 9]
    
    0 讨论(0)
提交回复
热议问题