Python slice first and last element in list

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

    One way:

    some_list[::len(some_list)-1]
    

    A better way (Doesn't use slicing, but is easier to read):

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

    You can do it like this:

    some_list[0::len(some_list)-1]
    
    0 讨论(0)
  • 2020-12-02 18:29

    These are all interesting but what if you have a version number and you don't know the size of any one segment in string from and you want to drop the last segment. Something like 20.0.1.300 and I want to end up with 20.0.1 without the 300 on the end. I have this so far:

    str('20.0.1.300'.split('.')[:3])
    

    which returns in list form as:

    ['20', '0', '1']
    

    How do I get it back to into a single string separated by periods

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

    Fun new approach to "one-lining" the case of an anonymously split thing such that you don't split it twice, but do all the work in one line is using the walrus operator, :=, to perform assignment as an expression, allowing both:

    first, last = (split_str := a.split("-"))[0], split_str[-1]
    

    and:

    first, last = (split_str := a.split("-"))[::len(split_str)-1]
    

    Mind you, in both cases it's essentially exactly equivalent to doing on one line:

    split_str = a.split("-")
    

    then following up with one of:

    first, last = split_str[0], split_str[-1]
    first, last = split_str[::len(split_str)-1]
    

    including the fact that split_str persists beyond the line it was used and accessed on. It's just technically meeting the requirements of one-lining, while being fairly ugly. I'd never recommend it over unpacking or itemgetter solutions, even if one-lining was mandatory (ruling out the non-walrus versions that explicitly index or slice a named variable and must refer to said named variable twice).

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

    Another python3 solution uses tuple unpacking with the "*" character:

    first, *_, last = range(1, 10)
    
    0 讨论(0)
  • 2020-12-02 18:31

    Utilize the packing/unpacking operator to pack the middle of the list into a single variable:

    >>> l = ['1', 'B', '3', 'D', '5', 'F']
    >>> first, *middle, last = l
    >>> first
    '1'
    >>> middle
    ['B', '3', 'D', '5']
    >>> last
    'F'
    >>> 
    

    Or, if you want to discard the middle:

    >>> l = ['1', 'B', '3', 'D', '5', 'F']
    >>> first, *_, last = l
    >>> first
    '1'
    >>> last
    'F'
    >>> 
    
    0 讨论(0)
提交回复
热议问题