Python slice first and last element in list

后端 未结 17 1363
有刺的猬
有刺的猬 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:48

    More General Case: Return N points from each end of list

    The answers work for the specific first and last, but some, like myself, may be looking for a solution that can be applied to a more general case in which you can return the top N points from either side of the list (say you have a sorted list and only want the 5 highest or lowest), i came up with the following solution:

    In [1]
    def GetWings(inlist,winglen):
        if len(inlist)<=winglen*2:
            outlist=inlist
        else:
            outlist=list(inlist[:winglen])
            outlist.extend(list(inlist[-winglen:]))
        return outlist
    

    and an example to return bottom and top 3 numbers from list 1-10:

    In [2]
    GetWings([1,2,3,4,5,6,7,8,9,10],3)
    
    #Out[2]
    #[1, 2, 3, 8, 9, 10]
    
    0 讨论(0)
  • 2020-12-02 18:49

    Python 3 only answer (that doesn't use slicing or throw away the rest of the list, but might be good enough anyway) is use unpacking generalizations to get first and last separate from the middle:

    first, *_, last = some_list
    

    The choice of _ as the catchall for the "rest" of the arguments is arbitrary; they'll be stored in the name _ which is often used as a stand-in for "stuff I don't care about".

    Unlike many other solutions, this one will ensure there are at least two elements in the sequence; if there is only one (so first and last would be identical), it will raise an exception (ValueError).

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

    You can use something like

    y[::max(1, len(y)-1)]
    

    if you really want to use slicing. The advantage of this is that it cannot give index errors and works with length 1 or 0 lists as well.

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

    Some people are answering the wrong question, it seems. You said you want to do:

    >>> first_item, last_item = some_list[0,-1]
    >>> print first_item
    '1'
    >>> print last_item
    'F'
    

    Ie., you want to extract the first and last elements each into separate variables.

    In this case, the answers by Matthew Adams, pemistahl, and katrielalex are valid. This is just a compound assignment:

    first_item, last_item = some_list[0], some_list[-1]
    

    But later you state a complication: "I am splitting it in the same line, and that would have to spend time splitting it twice:"

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

    So in order to avoid two split() calls, you must only operate on the list which results from splitting once.

    In this case, attempting to do too much in one line is a detriment to clarity and simplicity. Use a variable to hold the split result:

    lst = a.split("-")
    first_item, last_item = lst[0], lst[-1]
    

    Other responses answered the question of "how to get a new list, consisting of the first and last elements of a list?" They were probably inspired by your title, which mentions slicing, which you actually don't want, according to a careful reading of your question.

    AFAIK are 3 ways to get a new list with the 0th and last elements of a list:

    >>> s = 'Python ver. 3.4'
    >>> a = s.split()
    >>> a
    ['Python', 'ver.', '3.4']
    
    >>> [ a[0], a[-1] ]        # mentioned above
    ['Python', '3.4']
    
    >>> a[::len(a)-1]          # also mentioned above
    ['Python', '3.4']
    
    >>> [ a[e] for e in (0,-1) ] # list comprehension, nobody mentioned?
    ['Python', '3.4']
    
    # Or, if you insist on doing it in one line:
    >>> [ s.split()[e] for e in (0,-1) ]
    ['Python', '3.4']
    

    The advantage of the list comprehension approach, is that the set of indices in the tuple can be arbitrary and programmatically generated.

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

    Actually, I just figured it out:

    In [20]: some_list[::len(some_list) - 1]
    Out[20]: ['1', 'F']
    
    0 讨论(0)
提交回复
热议问题