Python中特定索引之间的搜索列表

时间:2016-05-23 12:44:33

标签: python list loops search

我需要创建一个函数来搜索特定索引之间的列表项。

我想要列表的开始和停止索引,我想找到列表中项目的位置。

例如:

def find(list, word, start=0, stop=-1):
    print("In function find()")

    for item in list:
        if item == word:
            return list[start:stop].index(word)

n_list = ['one', 'five', 'three', 'eight', 'five', 'six', 'eight']
print(find(n_list, "eight", start=4, stop=7 ))

此代码将返回" 2",因为单词" 8"列表[4:7]中的索引位置为2。

我的问题:如何更改此代码以便它返回" 6"?如果我删除[4:7],它会给我" 3"因为这个词"八"也处于[3]位置。

编辑:忘了说谢谢!

3 个答案:

答案 0 :(得分:2)

你不能简单地添加开始吗?

def find(list, word, start=0, stop=-1):
print("In function find()")

for item in list:
    if item == word:
        return start + list[start:stop].index(word)

答案 1 :(得分:1)

如果您认为可以信任以startstop为特色的范围,您可以将其变成一个单行:

n_list[start:stop].index(word)+start

答案 2 :(得分:0)

不需要for循环:

def find(list, word, start=0, stop=-1)
    '''Find word in list[start:stop]'''
    try:
       return start + list[start:stop].index(word)
    Except ValueError:
       raise ValueError("%s was not found between indices %s and %s"%(word, start, stop))