Skip to main content
 首页 » 编程设计

python之切片 python 列表

2024年10月25日9落叶无声

我有一个 python 列表如下:

>>>list1 = ['Mary','had','a','little','lamb','which','was','very','naughty'] 

现在我想创建一个包含从little 到very 元素的子列表。所以我做了以下事情:

>>> list1[list1.index('little'):list1.index('very')+1] 
['little', 'lamb', 'which', 'was', 'very'] 

我想做的不是指定整个元素,而是使用 in 函数检查元素中的子字符串,然后像这样对列表进行切片:

>>> list1[list1.index('lit'):list1.index('ver')+1] 

我该怎么做?

请您参考如下方法:

正如我在之前的回答中所说,您不需要使用 list.index 方法,您可以使用以下更快的函数,并且您可以对元素应用任何计算:

def drop(iterable,start,end): 
 
    for i,x in enumerate(iterable): 
        if x==start : 
            for y in iterable[i:]: 
                if y!=end and 'sub_string' in y: #or 'sub_string' not in y 
                    yield y 
                else: 
                    #based on your problem do stuff 
                    #yield end 
                    break