Skip to main content
 首页 » 编程设计

Python 3之查找列表的哪个索引包含特定字符串作为子字符串

2025年05月04日24lautakyan007

我正在编写以下代码:

def findLine(prog, target): 
   for l in range(0, len(prog)-1): 
      progX = prog[l].split() 
      for i in range(0, len(progX)): 
         if progX[i] == target: 
            a = progX[i] 

...但我需要一种方法来查找 prog 的哪个索引包含 a。该程序的示例输入是:

findLine(['10 GOTO 20', '20 END'], '20')

问题本身应该比我自己解释得更好:
定义一个函数 findLine(prog, target) 来执行以下操作。假设 prog 是包含 BASIC 程序的字符串列表,如 getBASIC() 生成的类型;假设 target 是一个包含行号的字符串,它是 GOTO 语句的目标。该函数应返回索引 i(介于 0 和 len(prog)-1 之间的数字),这样 prog[i] 就是标签等于目标的行。

示例输入/输出:如果你调用 findLine(['10 GOTO 20','20 END'],'10') 那么输出应该为 0,因为列表的第 0 项是标签为 10 的行。

那么,如何找到包含 ans 作为子字符串的第一个索引?在此先感谢您的帮助。

请您参考如下方法:

在我看来你很接近......

def findLine(prog, target): 
   for l in range(0, len(prog)):  #range doesn't include last element. 
      progX = prog[l].split() 
      #you probably only want to check the first element in progX 
      #since that's the one with the label 
      if progX[0] == target: 
          return l  #This is the one we want, return the index 
 
      #Your code for comparison 
      #for i in range(0, len(progX)): 
      #   if progX[i] == target: 
      #      a = progX[i] 

使用 enumerate 可以更好地完成这部分:

def findLine(prog, target): 
   for l,line in enumerate(prog): 
      progX = line.split() 
      if progX[0] == target: 
          return l  #This is the one we want, return the index 

如果你真的感兴趣,这可以在 python 中用 1 行来完成:

def findLine(prog,target): 
    return next(i for i,line in enumerate(prog) if line.split()[0] == target) 

该行中发生了很多事情,但这是一个相当常见的习语。它使用带有“生成器表达式”的 next 函数。