Skip to main content
 首页 » 编程设计

python之如何从 python 中列表的特定部分开始检查

2025年05月04日14jiqing9006

给出下面的列表:

#123 
*21 
*23 
*56 
*1 
*3 
#923 
*21 
*23 
*56 
*1 
*3 
#165 
... 

我想先找到带有#的特定行

例如:#923

然后打印所有以 * 为前缀的数字,直到下一次出现以 # 开头的行。

这是我尝试过的方法,但它不起作用:

for i in data: 
     ndata = i.split("::") 
     check = list(ndata[0]) 
     if check[0] == '*': 
        songs += ndata[0] + "\n" 
     if check[0] == '#': 
        break 

它确实会打印 * 并在以 # 开头的行上换行,但问题是它是从第一行开始的,而不是从包含 #923 的行开始的。

我将不胜感激任何帮助和提示!

请您参考如下方法:

您可以使用 itertools.dropwhile 删除行直到到达您想要的行然后循环直到您得到以 # 开头的行

from itertools import dropwhile    
def section(fle, start, stop): 
    with open(fle) as f: 
        # consume lines until we get to our start line 
        drop = dropwhile(lambda x: x.strip() != start, f) 
        # skip start 
        next(drop, "") 
        # loop starting at line after start line 
        for line in drop: 
            # if we reach stop line break 
            if line.startswith(stop): 
                break 
            # else we just yield the line 
            yield line.rstrip() 

输出:

In [4]: list(section("in.txt", "#923", "#")) 
Out[4]: ['*21', '*23', '*56', '*1', '*3'] 

要处理从 start 开始并由以 # 开头的行分隔的多个部分:

from itertools import dropwhile, groupby 
 
 
def section(fle, start, end): 
    with open(fle) as f: 
        grps = groupby(dropwhile(lambda x: x.strip() != start, f), 
                       key=lambda x: x.startswith(end)) 
        for k, v in grps: 
            if not k: 
                yield list(map(str.strip,v)) 

演示:

n [13]: cat in.txt 
(4.471719725275173E-003,2.163649191486555E-002) 
(6.471719725275173E-003,2#123 
*21 
*23 
*56 
*1 
*3 
#923 
*21 
*23 
*56 
*1 
*3 
#165.163649191486555E-002) 
*210 
*230 
*560 
*10 
*30 
#165.163649191486555E-002) 
In [14]: list(section("in.txt", "#923", "#")) 
Out[14]: [['*21', '*23', '*56', '*1', '*3'], ['*210', '*230', '*560', '*10', '*30']]