【问题标题】: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


【解决方案1】:

我在其他地方找到了这个答案: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]

【讨论】:

    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多