2016-05-23 70 views
0

我需要創建一個函數來搜索特定索引之間的列表項。Python中特定索引之間的搜索列表

我想有一個開始和列表停止索引,我想找到的項目列表中的位置。

例如:

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」,因爲字 「八」 是在2在列表中的索引位置[4:7]。

我的問題:我怎樣才能改變這種代碼,以便它返回「6」?如果我刪除[4:7],它會給我「3」,因爲單詞「8」也在[3]位置。

編輯:忘了說聲謝謝!

+0

你總是想要得到你的單詞的最後一個索引嗎? –

+0

該函數返回「2」是因爲你正在調用'list [start:stop]'上的索引本身就是一個列表 – Tanu

回答

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

注意:如果'word'在列表中,但在片外,這將失敗。 –

1

如果假定範圍特點startstop是可以信任的,你可以把它變成一個班輪:

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

如果元素不在切片中,這會拋出一個'ValueError',所以你可能想把它包裝到'try/except'中。否則罰款。 –

+0

@tobias_k如果停止> len(list):return'? – user2572329

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))