在列表上运行,查找索引,python

时间:2010-11-04 13:08:19

标签: python indexing find

我应该从单词列表中找出一个项目的索引。 功能:

def index(lst_words, word):

应返回wordlst_words的索引。 e.g。

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

回复0 为什么这个不适合我?

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

2 个答案:

答案 0 :(得分:3)

你可能意味着

  
    
      

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

    
  

不是

  
    
      

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

    
  

这不是搜索字符串,而是搜索列表。它会匹配

  
    
      

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

    
  

答案 1 :(得分: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