Python 如何使用函数查找单词在列表中的位置?

Python 如何使用函数查找单词在列表中的位置?,python,python-3.x,Python,Python 3.x,我知道这个问题在这里被问了很多次,但没有找到一个充分的答案 我需要找到单词在列表中的位置,当我运行代码时,它会给我None 代码如下: words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple'] def get_position(words, type_word): for idx, value in enumerate(words): if v

我知道这个问题在这里被问了很多次,但没有找到一个充分的答案

我需要找到单词在列表中的位置,当我运行代码时,它会给我
None

代码如下:

words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple']

def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value in words == type_word:
            return idx
        

positions = get_position(words, 'Apple')
print(positions)
首选输出:

[2, 3, 8] 

如果使用
return
,则函数将返回要返回的值。同样的情况也发生在代码中,它返回第一个匹配的值,而不是进一步检查

使用
yield
或临时列表保存匹配结果,然后返回

def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value == type_word:
            yield idx


您必须声明一个空列表,并在找到匹配项时将索引附加到列表中。 然后在循环之后,您必须返回列表。 代码如下所示:

words = ['Banana', 'Banana', 'Apple', 'Apple', 'Pear', 'Peach', 'Grapefruit', 'St', 'Apple']

def get_position(words, type_word):
    ret = []
    for idx, value in enumerate(words):
        if value in words == type_word:
            ret.append(idx)
    return ret
        

positions = get_position(words, 'Apple')
print(positions)

您可以使用列表理解

使用:

输出:

>>> get_position(words, "Apple")
[2, 3, 8]

以下是解决此问题的另一种方法:

words=[“香蕉”、“香蕉”、“苹果”、“苹果”、“梨”、“桃”、“柚子”、“圣”、“苹果”]
def get_索引(lst_来源):
lst=[]
对于范围内的i(len(lst_from)):
index=lst_从[i:]开始。index('Apple')+i
如果索引不在lst中:
lst.append(索引)
返回lst

如果words中的值==键入单词
是错误的做法。您已经在迭代
单词
,因此您知道值在列表中。只需使用
if value==type\u word
。使用
if value in words==type\u word
检查我的答案
返回后的中断是无法到达的;此外,这不会返回列表。@augurar很抱歉,草稿已提交、更新。
如果words==type\u word中的值不正确。如何返回单个值并将该代码放入函数中?(以我问题的格式)?您想要一个列表作为输出。返回单个值是什么意思?用
if value==type\u word
替换
if value==type\u word
。您的函数现在将返回与
words
中第一次出现的
type\u word
对应的索引。
outlist = []
def get_position(words, type_word):
    for idx, value in enumerate(words):
        if value == type_word:
            outlist.append(idx)
    return outlist

def get_position(words, type_word):
    return [idx for idx, w in enumerate(words) if w == type_word]
>>> get_position(words, "Apple")
[2, 3, 8]