【问题标题】:how do i find the positions of mulitple occurrences of a word in a list in python? [duplicate]如何在python的列表中找到一个单词多次出现的位置? [复制]
【发布时间】:2017-01-26 23:01:23
【问题描述】:

我正在尝试获取用户输入的单词的位置,但是如果单词在句子中只出现一次,我只能找到位置,如果输入的单词在句子中出现多次,我如何找到位置句子?

if varInput in varwords:
    print ("Found word")
    #prints total number of words
    print("The total number of words is: "  + str(len(varwords)))#http://stackoverflow.com/questions/8272358/how-do-i-calculate-the-number-of-times-a-word-occurs-in-a-sentence-python
    #finds out how many times the word occurs in the sentence
    wordOcc = (varwords.count(varInput))
    #if word occurence = 1 then print the position of the word
    if wordOcc ==1:
        pos = varwords.index(varInput)
        pos = pos+1
        print("the word "+varInput+" appears at position:")
        print(pos)

    else if wordOcc =>2:
        pos1 = varwords.index(varInput)

【问题讨论】:

标签: python


【解决方案1】:

.index 方法只会返回第一次出现;它不是产生不同值的迭代器。

但是,有一种非常简单的方法可以找到所有出现的事件。您可以遍历 words 数组的索引,并添加 item 为指定单词的索引:

indexes = [i for i in range(len(sentence)) if sentence[i] == word]

这会将所有出现的单词作为一个列表返回,如果没有找到该单词,则返回一个空列表(带有len(indexes)==0)。

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 2021-05-09
    • 2012-05-13
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多