例如,我的程序存储一个句子,然后要求用户输入句子中的单词。但是有一种方法我可以使用迭代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 :(得分:0)
我在其他地方找到了这个答案:How to find all occurrences of an element in a list?
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
例如,
my_list = [1, 1, 2, 3]
indices = [i for i, x in enumerate(my_list) if x == 1]
print(indices)
打印[0,1]
答案 1 :(得分: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)