一种访问列表中的后两个元素的优雅方式? [英] Elegant way to access last two and next two elements in a list?
问题描述
我需要访问前两个元素和后两个元素(如果存在).例如 [...,a,b,c,d,e,..]
->对于 c
我想要 abcde
.
I need to access the previous two and next two elements(if exist).
e.g. [..., a, b, c, d, e, ..]
-> For c
I want abcde
.
这对于列表中间的元素很容易,但是在开始和结束时将导致索引超出范围错误.如果列表较小,它将变得更加复杂.
This is easy for elements in the middle of a list, but in the beginning and end it will cause Index out of range errors. And if the list is smaller it becomes even more complicated.
我可以用一堆 if
- elif
- elif
- else
语句来做到这一点案件,但有没有简洁而优雅的方法来做到这一点?
I can do it with a bunch of if
-elif
-elif
--else
statements for all the cases, but is there any concise and elegant way to accomplish this?
我正在使用python 2.7
I'm using python 2.7
推荐答案
只使用切片(但要注意负索引):
Just use slicing (but be careful about negative indices):
inputlist[max(0, index - 2):index + 3]
将为您提供一个围绕着 index
最多5个元素的窗口;前2个,后2个.
will get you a window of up to 5 elements around index
; 2 before and 2 after.
max()
调用可确保起始索引的上限为 0
或更高.
The max()
call ensures that the start index is capped to 0
or up.
这将与您用来生成索引的任何方法一起使用.假设您正在使用循环以及 enumerate()
来跟踪索引:
This'll work with whatever method you used to produce your index. Say you are using a loop, together with enumerate()
to keep track of the index:
def window(inputlist, index):
return inputlist[max(0, index - 2):index + 3]
for index, elem in enumerate(inputlist):
print window(inputlist, index)
或通过 list.index()
找到了元素:
print window(inputlist, inputlist.index('ham'))
演示:
>>> def window(inputlist, index):
... return inputlist[max(0, index - 2):index + 3]
...
>>> window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 1)
['foo', 'bar', 'baz', 'spam']
>>> window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 2)
['foo', 'bar', 'baz', 'spam', 'ham']
>>> window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 4)
['baz', 'spam', 'ham', 'eggs']
>>> window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 5)
['spam', 'ham', 'eggs']
这篇关于一种访问列表中的后两个元素的优雅方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!