有没有一种方法可以打印出数组中的多个对象?

2024-09-25 00:24:34 发布

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

例如,我的程序存储了一个句子,然后要求用户从这个句子中输入一个单词。但是,如果单词在句子中出现两次,有没有一种方法可以使用迭代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)

Tags: 方法用户程序hello单词aresentence句子
2条回答

生成一个返回匹配索引列表的函数。如果找不到单词,则返回空列表。如果只返回一次,则只返回列表中的一个元素。例如

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)

我在别处找到了这个答案: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]

相关问题 更多 >