Python 如何从列表中删除从开始到结束的范围enclusive
我有点不知所措,不知道该怎么做。任何帮助都将不胜感激。简单地说Python 如何从列表中删除从开始到结束的范围enclusive,python,list,Python,List,我有点不知所措,不知道该怎么做。任何帮助都将不胜感激。简单地说 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)
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
"""
应该足够了。您可以复制列表并删除不需要的部分
del alist[start:end+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:];")
这应该满足您的要求:
>>> inlist = [8,7,6,5,4,3,2,1]
>>> outlist = inlist[:]
>>> del outlist[2:6]
>>> outlist
[8, 7, 2, 1]
def remove_section(alist, start, end):
return alist[:start] + alist[end+1:]