在列表中操作,查找索引,python

0 投票
2 回答
1154 浏览
提问于 2025-04-16 06:33

我需要从一个单词列表中找到某个单词的位置。这个函数:

def index(lst_words, word):

应该返回 wordlst_words 中的位置。比如:

>>> index (['how, 'to', 'find'], ['how'])

应该返回 0。为什么这个对我不管用呢?

def index (lst_words, word):
    find = lst_words.index(word)
    return find

2 个回答

3

你可能想要的是:

['how', 'to', 'find'].index('how').

而不是:

['how', 'to', 'find'].index(['how'])

这里不是在查找一个字符串,而是在查找一个列表。它会匹配:

['how', 'to', 'find', ['how']].index(['how'])

1
>>> def index(lst_words, word):
       find = lst_words.index(word)
       return find

>>> x = ['hello', 'foo', 'bar']
>>> index(x, 'bar')
2

这就是你可能想要表达的意思。当你想找到 bar 的位置时,你应该把 bar 作为一个字符串参数传入,而不是作为一个列表。因为你现在的列表其实是一个字符串的列表。

它们之间的区别是:

>>> x = ['bar']
>>> type(x)
<type 'list'>
>>> x = 'bar'
>>> type(x)
<type 'str'>

所以,如果你列表里的元素是另一个列表的话,你现在尝试做的事情就能成功。

>>> x = ['hello', 'foo', ['bar']]
>>> index(x, ['bar'])         # since bar is a list not a string
2

撰写回答