Python slice first and last element in list

2019-01-17 09:29发布

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', '5', 'F']

I want to do this (obviously [0,-1] is not valid syntax):

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

Some things I have tried:

In [3]: some_list[::-1]
Out[3]: ['F', '5', 'D', '3', 'B', '1']

In [4]: some_list[-1:1:-1]
Out[4]: ['F', '5', 'D', '3']

In [5]: some_list[0:-1:-1]
Out[5]: []
...

14条回答
啃猪蹄的小仙女
2楼-- · 2019-01-17 09:55

What about this?

>>> first_element, last_element = some_list[0], some_list[-1]
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-17 09:56

I found this might do this:

list[[0,-1]]
查看更多
够拽才男人
4楼-- · 2019-01-17 09:57

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]]
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-17 09:58
first, last = some_list[0], some_list[-1]
查看更多
我命由我不由天
6楼-- · 2019-01-17 09:59

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.

查看更多
放荡不羁爱自由
7楼-- · 2019-01-17 10:00

Actually, I just figured it out:

In [20]: some_list[::len(some_list) - 1]
Out[20]: ['1', 'F']
查看更多
登录 后发表回答