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

2024-04-20 13:18:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想在给定值前后提取3个值。e、 g.如果输入为2007,则输入前的3个值为:2004、2005、2006,输入后的3个值为:2008、2009、2010。如果输入是2014,那么我想在之前提取5个值,在之后提取1个值(总共6个值)。你知道吗

我可以用for循环来做这个,但是有没有更适合python的解决方案呢?你知道吗


Tags: 列表for逻辑解决方案条件ll个值
2条回答

使用切片:

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

列表切片就是为了这个,正如Daniel提到的。因为你所要求的不是一个标准用例,所以你必须编写你自己的函数。我找到了两种方法。你知道吗

第一种方法简单地区分了五种可能的情况,并相应地应用了列表切片。请注意,这里的if系列只起作用,因为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]

相关问题 更多 >