【问题标题】:Is there a way you can print out multiple objects in a array?有没有办法可以打印出数组中的多个对象?
【发布时间】:2017-03-07 19:12:22
【问题描述】:
例如,我的程序存储了一个句子,然后会要求用户输入句子中的一个单词。但是,如果单词在句子中出现两次,我可以使用迭代 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)
【问题讨论】:
标签:
python
arrays
string
elements
【解决方案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)