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

时间:2016-07-30 12:21:53

标签: python list subroutine

我的程序的目的是找到句子中单词的迭代位置,故障子程序如下:

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"作为句子的列表形式"运动的改变是动力的比例,并且是在正确的力量和#34;的正确线上进行的。现在,说我搜索"印象深刻"在splitString中,它返回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个"印象深刻的实例"但是没有将这些数量计入"实例"变量(看起来不可靠并且不起作用。)positionLibrary,用于存储(作为字符串)所找到的实例位置的记录,但不起作用。我相信这是因为该计划只返回第一个实施的位置。如11 impressed 11 impressed所示。

现在,如何使程序实际返回单词的第一个实例之后的任何位置并制作"实例"变量工作?我进行了广泛的搜索,但没有找到解决方案。

2 个答案:

答案 0 :(得分:0)

您不需要使用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

答案 1 :(得分:0)

如果您喜欢尝试这样的事情: -

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)