Python slice first and last element in list

后端 未结 17 1364
有刺的猬
有刺的猬 2020-12-02 17:54

Is there a way to slice only the first and last item in a list?

For example; If this is my list:

>>> some_list
[\'1\', \'B\', \'3\', \'D\',          


        
相关标签:
17条回答
  • 2020-12-02 18:32
    def recall(x): 
        num1 = x[-4:]
        num2 = x[::-1]
        num3 = num2[-4:]
        num4 = [num3, num1]
        return num4
    

    Now just make an variable outside the function and recall the function : like this:

    avg = recall("idreesjaneqand") 
    print(avg)
    
    0 讨论(0)
  • 2020-12-02 18:33
    first, last = some_list[0], some_list[-1]
    
    0 讨论(0)
  • 2020-12-02 18:36

    I found this might do this:

    list[[0,-1]]
    
    0 讨论(0)
  • 2020-12-02 18:38

    What about this?

    >>> first_element, last_element = some_list[0], some_list[-1]
    
    0 讨论(0)
  • 2020-12-02 18:40

    This isn't a "slice", but it is a general solution that doesn't use explicit indexing, and works for the scenario where the sequence in question is anonymous (so you can create and "slice" on the same line, without creating twice and indexing twice): operator.itemgetter

    import operator
    
    # Done once and reused
    first_and_last = operator.itemgetter(0, -1)
    
    ...
    
    first, last = first_and_last(some_list)
    

    You could just inline it as (after from operator import itemgetter for brevity at time of use):

    first, last = itemgetter(0, -1)(some_list)
    

    but if you'll be reusing the getter a lot, you can save the work of recreating it (and give it a useful, self-documenting name) by creating it once ahead of time.

    Thus, for your specific use case, you can replace:

    x, y = a.split("-")[0], a.split("-")[-1]
    

    with:

    x, y = itemgetter(0, -1)(a.split("-"))
    

    and split only once without storing the complete list in a persistent name for len checking or double-indexing or the like.

    Note that itemgetter for multiple items returns a tuple, not a list, so if you're not just unpacking it to specific names, and need a true list, you'd have to wrap the call in the list constructor.

    0 讨论(0)
  • 2020-12-02 18:43

    Just thought I'd show how to do this with numpy's fancy indexing:

    >>> import numpy
    >>> some_list = ['1', 'B', '3', 'D', '5', 'F']
    >>> numpy.array(some_list)[[0,-1]]
    array(['1', 'F'], 
          dtype='|S1')
    

    Note that it also supports arbitrary index locations, which the [::len(some_list)-1] method would not work for:

    >>> numpy.array(some_list)[[0,2,-1]]
    array(['1', '3', 'F'], 
          dtype='|S1')
    

    As DSM points out, you can do something similar with itemgetter:

    >>> import operator
    >>> operator.itemgetter(0, 2, -1)(some_list)
    ('1', '3', 'F')
    
    0 讨论(0)
提交回复
热议问题