2017-03-07 44 views
0

例如,我的程序存儲一個句子,然後會要求用戶輸入句子中的單詞。然而,如果在句子中出現兩次,我可以使用迭代python來打印單詞的位置。有沒有辦法可以打印出數組中的多個對象?

sentence = (' hello im jeffery hello who are you?') 

print (sentence) 

word = input('enter a word from the sentence') 

print (word) 

split = sentence.split(' ') 

if word in split: 

    posis = split.index() 

print (posis) 
+0

參見[這裏](http://stackoverflow.com/questions/6294179/how-to-find列表中元素的出現次數) – roganjosh

+0

[如何查找列表中所有元素的出現次數?](http://stackoverflow.com/questions/6294179/how-對發現,所有事件 - 的 - 一個元素,在-A-名單) – Aaron

回答

0

請返回匹配的列表的功能指數。如果找不到該單詞,它將返回一個空列表。如果只有一次,它只返回列表中的一個元素。例如,

def get_positions(word, sentence): 
    tokens = sentence.split(' ') 
    return [i for i, x in enumerate(tokens) if x == word] 

然後你只需要調用它來獲得結果:

sentence = "hello im jeffery hello who are you?" 
matching_indices = get_positions("hello", sentence) 

if len(matching_indices) < 1: 
    print("No matches") 
else: 
    for i in matching_indices: 
     print("Token matches at index: ", i) 
相關問題