Python中特定索引之间的搜索列表
我需要创建一个函数来搜索特定索引之间的列表项 我想要列表的开始和停止索引,我想要找到列表中项目的位置 例如:Python中特定索引之间的搜索列表,python,list,loops,search,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', '
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”,因为单词“八”在列表[4:7]中的索引位置为2
我的问题:如何更改此代码以使其返回“6”?如果我去掉[4:7],它会给我“3”,因为“8”这个词也在[3]的位置
编辑:忘了说谢谢了 您不能简单地添加start吗
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)
你不能简单地加上开始吗
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)
如果您假设以
开始
和停止
为特征的范围可以信任,则可以将其设置为一行:
n_list[start:stop].index(word)+start
如果您假设以
开始
和停止
为特征的范围可以信任,则可以将其设置为一行:
n_list[start:stop].index(word)+start
不需要
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))
不需要
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))
是否始终要获取单词的最后一个索引?函数返回“2”,因为您在
列表[start:stop]
上调用索引,而该列表本身就是一个列表。是否始终要获取单词的最后一个索引?函数返回“2”,因为您在列表[start:stop]上调用索引
这本身就是一个列表注意:如果word
在列表中但在切片之外,则此操作将失败。注意:如果word
在列表中但在切片之外,则此操作将失败。如果元素不在切片中,则会抛出ValueError
,因此您可能希望将其包装到try/except
中。否则可以。@tobias_k如果stop>len(列表)如何:return
?如果元素不在切片中,这将抛出一个ValueError
,因此您可能希望将其包装到try/except
中。否则可以。@tobias_k如果停止>len(列表):返回如何?