【问题标题】:Sample the neighbour value from a list从列表中采样邻居值
【发布时间】:2020-04-22 07:24:48
【问题描述】:

比方说,我有一个清单:

[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 中创建这样的函数?

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

谢谢。

【问题讨论】:

  • 为什么我的问题不喜欢?

标签: python list random sample


【解决方案1】:

类似这样的:

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))

【讨论】:

  • 如果 idx=11 它返回 [Oct, Nov, Dec]。如何返回 [Aug,Sep,Oct,Nov,Dec]?
【解决方案2】:
if index<=2 or :
   print(list[:5])
elif index>=len(list)-2:
   print(list[-5:])
else:
   print(list[index-2:index+2])

【讨论】:

    【解决方案3】:
    # 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多