【问题标题】:Accessing list from function从函数访问列表
【发布时间】:2016-02-09 11:55:10
【问题描述】:

我正在编写一个函数,用户输入文本和单词,如果单词在列表中,它会返回单词在列表中的位置。

list = ["hello", "goodbye", "name"]     

def fact(txt, my_list):
    text = txt.split()
    for i in range(0, len(my_list)):
        for j in range(0, len(text)):
            if(my_list[i] == text[i]):
                return my_list[i]

value = fact("hello, my name is", "name")
print(value)

但是,这似乎每次都没有返回。是否有任何特殊原因无法正常工作?

【问题讨论】:

  • 您的缩进似乎完全损坏了。
  • 请不要发布没有适当缩进的代码,尤其是python代码。
  • 由于在 Python 中缩进是语法的一部分,请确保您的代码正确缩进。
  • 你的预期输出是什么

标签: python list


【解决方案1】:

示例:

  def f(text, search):
        if search in text.split():
            print('Word "{}" has been found @ index: {}'.format(search, text.split().index(search)))

输出:

data = 'hello world, my name is -e'
f(data, '-e')

已找到单词“-e”@index: 5

【讨论】:

  • 该函数应该返回索引,而不是打印它。
【解决方案2】:

这很好用

def getword(word, text):
    text = text.replace(',', '') # remove ',' by nothing
    tmp = text.split(' ')   
    if word in tmp:
        print("word: [%s] find at index %s in this text:[ %s]" % (word, tmp.index(word), text))
        return tmp.index(word) 
    else:
        print("Did not find [%s] in [%s]" % (word, text))
        return -1


word = "what"
text = "Hello, I am groot, what is your name"

index = getword(word, text) 

【讨论】:

    猜你喜欢
    • 2021-04-17
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多