简体   繁体   English

Python切片符号仅采用列表的开始和结束部分?

[英]Python slice notation to take only the start and the end part of a list?

Is there a way to use the slice notation to take only the start and end of a list? 有没有一种方法可以使用切片表示法仅获取列表的开头和结尾?

eg 10 items from the start and 10 items from the end? 例如从开始起10个项目,从结束起10个项目?

Not directly… but it's very easy to use slicing and concatenation together to do it: 不是直接…但是将切片和串联一起使用非常容易:

>>> a = list(range(100))
>>> a[:10] + a[-10:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

Of course if there are fewer than 20 items in the list, you will get some overlapped values: 当然,如果列表中的项目少于20个,您将获得一些重叠值:

>>> a = list(range(15))
>>> a[:10] + a[-10:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

… but you're getting literally what you asked for: 10 items from the start, and 10 items from the end. ...但你得到的字面意思是你要求的:从一开始的10个项目和从最后的10个项目。 If you want something different, it's doable, but you need to define exactly what you want. 如果您想要不同的东西,那是可行的,但是您需要准确定义您想要的东西。

You can replace the items in the middle with an empty list 您可以将中间的项目替换为空列表

>>> a = list(range(100))
>>> a[10:-10] = []
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

Doing it this way doesn't give an overlap, just the entire list if there isn't enough items 这样做不会产生重叠,只有整个列表没有足够的项目

>>> a = list(range(15))
>>> a[10:-10] = []
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Even works in a sane way for @abarnert's case 甚至在@abarnert的情况下也能以理智的方式工作

>>> a = list(range(3))
>>> a[10:-10] = []
>>> a
[0, 1, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM