2012-10-20 51 views
2
my_list = ['apple', 'pear', 'orange', 'raspberry'] 

# I know that I'm always looking for pear. 
print 'pear' in my_list # prints True 

# I want to be able to get a key by its value. 
pear_key = my_list['pear'].key # should be 1 

# Print the next item in the list. 
print my_list[pear_key + 1] # should print orange 

我知道pear將永遠是我列表中的一個項目(不是位置雖然),我正在尋找一種方法來獲取該列表中的下一個項目的值,或者通過獲取當前的鍵通過知道它的價值並且通過一個(像我在上面的例子中那樣)或者通過使用諸如my_list.next之類的東西來推進它。有沒有辦法通過了解當前項目的值來獲取列表中的下一個項目?

回答

5
try: 
    pos = my_list.index('pear') 
    print my_list[pos + 1] 
    # orange 
except IndexError as e: 
    pass # original value didn't exist or was end of list, so what's +1 mean? 

你當然可以預先緩存的話,使用(認爲它可能是迭代工具對配方)

from itertools import tee 
fst, snd = tee(iter(my_list)) 
next(snd, None) 
d = dict(zip(fst, snd)) 

但你失去的事實,不管它是在原來的列表,或只是沒有一個合乎邏輯的下一個值。

2

使用此:

>>> my_list[my_list.index('pear') + 1] 
'orange' 

需要注意的是,如果這是在列表中的最後一個值,你會得到一個異常IndexError

1

您可以使用index在列表中找到某個特定值: -

try: 
    print my_list[my_list.index('pear') + 1] 
except (IndexError, ValueError), e: 
    print e 
2

而簡單的解決方案已經給出了,如果你想這樣做的一個通用的迭代,而不是一個列表,最簡單的答案是使用itertools.dropwhile()

import itertools 

def next_after(iterable, value): 
    i = itertools.dropwhile(lambda x: x != value, iterable) 
    next(i) 
    return next(i) 

其中可用於像這樣:

>>> next_after(iter(my_list), "pear") 
'orange' 

請注意,如果您正在處理列表,則這是一個較慢且不易讀的解決方案。這只是一個替代情況的說明。

你也可以產生一個版本更具描述性的錯誤:

​​
相關問題