【发布时间】:2016-09-20 08:33:56
【问题描述】:
我需要创建一个函数来搜索特定索引之间的列表项。
我想有一个列表的开始和停止索引,我想找到项目在列表中的位置。
例如:
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”,因为单词“八”在 list[4:7] 中 2 的索引位置。
我的问题:如何更改此代码以使其返回“6”?如果我删除 [4:7],它会给我“3”,因为“8”这个词也在 [3] 位置。
编辑:忘了说谢谢!
【问题讨论】:
-
你总是想得到你单词的最后一个索引吗?
-
该函数返回“2”,因为您正在调用
list[start:stop]上的索引,它本身就是一个列表