从列表中采样邻居值

Sample the neighbour value from a list

比方说,我有一个列表:

[Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]

我随机选择索引(比如 idx=4,因此 "May"),我希望我的函数 return

[Mar,Apr,May,Jun,Jul]

如果索引为 0(一月)或 1(二月),那么我希望我的函数为 return [Jan,Feb,Mar,Apr,May]。 returned 列表的长度始终为 5。

如何在Python3中创建这样的函数?

简单的问题,但为什么我的头开始爆炸?

谢谢。

像这样:

monthes = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

def myfunc(choices, index):
    start = min(max(index - 2, 0), len(choices) - 5)
    return choices[start:start+5]

print(myfunc(monthes, 4))
print(myfunc(monthes, 0))
print(myfunc(monthes, 1))
if index<=2 or :
   print(list[:5])
elif index>=len(list)-2:
   print(list[-5:])
else:
   print(list[index-2:index+2])
# List of months
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# Get input
index = int(input())

def getMonths(index):
  if index>1 and index<len(months)-2:
    # Return 5 elements in the neighbourhood of the index
    return months[index-2:index] + months[index:index+3]
  elif index<=1 and index>=0: 
    # Return first 5 if index less than 2
    return months[:5]
  elif index>len(months)-2:
    # Return last 5 elements if index greater
    return months[len(months)-5:]
  else:
    # Return -1 for invalid index
    return -1
# Print output
print(getMonths(index))