假设我有一个列表:
[Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
并且我随机选择索引(假设idx = 4,因此为“ May”),我希望函数返回
[Mar,Apr,May,Jun,Jul]
如果索引为0(1月)或1(2月),那么我希望函数返回[Jan,Feb,Mar,Apr,May]
。返回列表的长度始终为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]
else:
# Return -1 for invalid index
return -1
# Print output
print(getMonths(index))