在python列表中提取位置之前和之后的值

时间:2017-11-07 17:14:58

标签: python list numpy

我想根据以下逻辑有条件地从python列表中提取值:

ll = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015]

我想在给定值之前和之后提取3个值。例如如果输入是2007,则之前的3个值将是:2004年,2005年,2006年及之后将是:2008年,2009年,2010年。如果输入是2014年,那么我想提取之前的5个值和之后的1个值(总计6个值)。

我可以使用for循环来做这个,但是有更多的pythonic解决方案吗?

2 个答案:

答案 0 :(得分:1)

正如Daniel所说,列表切片正是为此而做的。因为您要求的不是标准用例,所以您必须编写自己的函数。我发现了两种方法。

第一个简单区分五种可能的情况并相应地应用列表切片。请注意,此处的if-series仅起作用,因为return语句退出函数。它基本上等同于if-else。

第二个函数通过巧妙地使用ll.remove()来减少代码行数,但这有点难以理解。

任何一个都可以。

ll = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
      2011, 2012, 2013, 2014, 2015]

def six_neighbours_simple(year):
    idx = ll.index(year) # get location of year in array
    # take care of the left end
    if idx == 0:
        return ll[1:7]
    if idx < 3:
        return ll[:idx] + ll[idx+1:7]
    # take care of the right end
    if idx == len(ll) - 1:
        return ll[-7:-1]
    if idx > len(ll) - 4:
        return ll[-7:idx] + ll[idx+1:]
    # ELSE
    return ll[idx-3:idx] + ll[idx+1:idx+4]

def six_neighbours_short(yr):
    idx = ll.index(yr) # save location of yr
    years = ll[:] # copy list into new variable so we don't change it
    years.remove(yr) # remove selected year
    left_slice = idx-3 # start of range
    left_slice = min(max(0,left_slice),len(years)-6) # account for edges
    right_slice = left_slice+6 # end of range is straightforward now
    return years[left_slice:right_slice]

答案 1 :(得分:0)

使用切片:

>>> ll = [2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015]
>>> idx = ll.index(2002)
>>> ll[max(idx-5,0):idx+2]
[2001, 2002, 2003]
>>> idx = ll.index(2013)
>>> ll[max(idx-5,0):idx+2]
[2008, 2009, 2010, 2011, 2012, 2013, 2014]