我的程序的目的是找到一个句子中单词的迭代位置,出现故障的子程序如下所示
def analyse(splitString):
wordToSearch = input("What word are you searching for instances of? ").lower()
for word in splitString:
positionLibrary = ""
positionInSplitString = 0
instances = 0
if word == wordToSearch:
position = splitString.index(word)
positionLibrary += str(position)
print (position, word)
instances += 1
positionInSplitString += 1
return (positionLibrary, instances, wordToSearch)
让“splitString”作为句子的列表形式,“运动的变化总是与施加的动力成比例的,并且是在施加该力的右边行上进行的”。现在,假设我在splitString中搜索“impressed”,它返回What word are you searching for instances of? impressed
11 impressed
11 impressed
['the', 'alteration', 'of', 'motion', 'is', 'ever', 'proportional', 'to', 'the', 'motive', 'force', 'impressed', 'and', 'is', 'made', 'in', 'the', 'right', 'line', 'on', 'which', 'that', 'force', 'is', 'impressed']
wordToSearch impressed
instances 1
positionLibrary 11
它告诉我程序不知何故知道有2个“impressed”的实例,但没有将这些实例的数量计入“instances”变量(这似乎不可靠,也不起作用。)positionLibrary(作为字符串)存储找到的实例位置的记录,却不起作用。我相信这是因为程序只返回第一个“impressed”实例的位置,如11 impressed
11 impressed
所示
现在,我如何让程序在单词的第一个实例之后返回任何位置,并让“instances”变量工作?我到处找了,没有找到解决办法
您不需要使用
index()
方法,因为您已经在splitString
中循环了。您只需要一个索引或计数器来跟踪您所处的迭代。为此,可以使用enumerate
这个呢:
如果您确实想使用
index()
,它可以使用第二个参数,这是您应该开始搜索的位置。例如如果你想试试this:- 你知道吗
相关问题 更多 >
编程相关推荐