检索lis中字符串的多个迭代位置

2024-10-01 19:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序的目的是找到一个句子中单词的迭代位置,出现故障的子程序如下所示

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”变量工作?我到处找了,没有找到解决办法


Tags: oftheinstances实例程序forisposition
2条回答

您不需要使用index()方法,因为您已经在splitString中循环了。您只需要一个索引或计数器来跟踪您所处的迭代。为此,可以使用enumerate

这个呢:

def analyse(splitString, wordToSearch):
    positionLibrary = [j for j, word in enumerate(splitString) if word == wordToSearch]
    instances = len(positionLibrary)
    return (positionLibrary, instances)

splitString = ['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']
print analyse(splitString, 'impressed')
# ([11, 24], 2)

如果您确实想使用index(),它可以使用第二个参数,这是您应该开始搜索的位置。例如

print splitString.index('impressed') # 11
print splitString.index('impressed', 0) # 11
print splitString.index('impressed', 12) # 24

如果你想试试this:- 你知道吗

def index_count_search(sentance, search):
     searchedList = map(lambda x:x[0], filter(lambda (index, value): search == value, enumerate(sentance.split())))
     return (",".join(searchedList), len(searchedList), search)


wordToSearch = input("What word are you searching for instances of? ").lower()
print analyse("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".lower(), wordToSearch)

相关问题 更多 >

    热门问题