单个切片从 Python 列表的开头和结尾获取元素?
Single slice getting elements from beginning and end of list in Python?
Python 中列表的第一个和最后 N 个元素可以使用以下方法获取:
N = 2
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[:N] + my_list[-N:])
# [0, 1, 4, 5]
是否可以用纯 Python 中的单个切片来做到这一点?我试过my_list[-N:N]
,它是空的,my_list[N:-N]
,它给出了我不想要的元素。
对于内置类型,切片根据定义是连续的 - slice represents a start, end and step between them。单个切片操作无法表示不连续的元素,例如列表的头和尾。
Python 中列表的第一个和最后 N 个元素可以使用以下方法获取:
N = 2
my_list = [0, 1, 2, 3, 4, 5]
print(my_list[:N] + my_list[-N:])
# [0, 1, 4, 5]
是否可以用纯 Python 中的单个切片来做到这一点?我试过my_list[-N:N]
,它是空的,my_list[N:-N]
,它给出了我不想要的元素。
对于内置类型,切片根据定义是连续的 - slice represents a start, end and step between them。单个切片操作无法表示不连续的元素,例如列表的头和尾。