Python3-查找列表的哪个索引包含作为子字符串的特定字符串
我正在编写以下代码:Python3-查找列表的哪个索引包含作为子字符串的特定字符串,python,list,python-3.x,Python,List,Python 3.x,我正在编写以下代码: 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
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是包含基本程序的字符串列表,如getBASIC()生成的类型;假设target是一个包含行号的字符串,行号是GOTO语句的目标。函数应该返回索引i(0和len(prog)-1之间的数字),这样prog[i]就是其标签等于target的行 示例输入/输出:如果您调用 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]
使用枚举
可以更好地完成此部分:
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
for index, line in enumerate(prog):
line_parts = line.split()
for part in line_parts:
if part == target:
# Figure out what to do here.
# Remember that 'index' is the index of the line you are examining.
如果您真的感兴趣,可以在python的一行中完成:
def findLine(prog,target):
return next(i for i,line in enumerate(prog) if line.split()[0] == target)
这一行有很多内容,但这是一个相当常见的习语。它使用带有“生成器表达式”的
next
函数。您跳过了最后一行
范围生成一系列的所有内容,包括但不包括第二个参数:
>>> list(range(5))
[0, 1, 2, 3, 4]
查看如何有五个值,但5
不是其中之一吗?(如果range
的第一个参数是0
,则可以忽略它。)
一种更具python风格的方法是使用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
for index, line in enumerate(prog):
line_parts = line.split()
for part in line_parts:
if part == target:
# Figure out what to do here.
# Remember that 'index' is the index of the line you are examining.
我不喜欢像这样返回
-1
,因为-1
对于列表来说是一个完全可以接受的索引——但它不会给你想要的元素。如果你愿意,你可以做一些不同的事情,比如抛出indexer。基本上,我是为了与字符串find()相似方法。您也可以使用line.startswith(target)
而不是line.split()[0]==target
@gonz--我考虑过这个问题,但我不知道BASIC以及它如何处理语句标签。我看到的startswith
的问题是:1)我不知道标签前是否有空格,2)在第100行末尾搜索10将返回True。。。