2011-05-19 54 views
3
def remove_section(alist, start, end): 
    """ 
    Return a copy of alist removing the section from start to end inclusive 

    >>> inlist = [8,7,6,5,4,3,2,1] 
    >>> remove_section(inlist, 2, 5) 
    [8, 7, 2, 1] 
    >>> inlist == [8,7,6,5,4,3,2,1] 
    True 
    >>> inlist = ["bob","sue","jim","mary","tony"] 
    >>> remove_section(inlist, 0,1) 
    ['jim', 'mary', 'tony'] 
    >>> inlist == ["bob","sue","jim","mary","tony"] 
    True 
    """ 

我對於如何去做這件事感到有點難住,任何幫助都將不勝感激。如何從列表中刪除從開始到結束的範圍

回答

3

這應該做你想要什麼:

def remove_section(alist, start, end): 
    return alist[:start] + alist[end+1:] 
3

只需

del alist[start:end+1] 

應該夠了。

1

你可以複製列表,並刪除部分你不想

newlist = alist[:] 
del newlist[start:end] 

或者你可以將兩個片

newlist = alist[start:] + atlist[end+1:] 

兩種方法的快速時間:

print timeit.repeat("b=range(100);a = b[:]; del a[2:8]") 
print timeit.repeat("b=range(100);a = b[2:] + b[8:];") 

第一種方法的速度是第二種方法的兩倍。

0

最容易複製序列,然後刪除一個切片。

>>> inlist = [8,7,6,5,4,3,2,1] 
>>> outlist = inlist[:] 
>>> del outlist[2:6] 
>>> outlist 
[8, 7, 2, 1] 
相關問題