Python slice first and last element in list

后端 未结 17 1471
有刺的猬
有刺的猬 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: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).

提交回复
热议问题