Python切片列表中的第一个和最后一个元素 [英] Python slice first and last element in list
本文介绍了Python切片列表中的第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法只分割列表中的第一项和最后一项?
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']
我想要做到这一点(显然[0,-1]
是无效的语法):
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'
我尝试过的一些事情:
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]: []
...
推荐答案
一种方法:
some_list[::len(some_list)-1]
更好的方法(不使用切片,但更易于阅读):
A better way (Doesn't use slicing, but is easier to read):
[some_list[0], some_list[-1]]
这篇关于Python切片列表中的第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文