2008-11-27 54 views

回答

0

迭代器只有next()方法,所以你不能向前看或向後看,你只能得到下一個項目。

如果迭代列表或元組,則枚舉(可迭代)會很有用。

-7

最簡單的方法是搜索列表中的項目:

def get_previous(l, item): 
    idx = l.find(item) 
    return None if idx == 0 else l[idx-1] 

當然,這只是工作,如果列表中只有唯一項目。另一種解決方案是:

for idx in range(len(l)): 
    item = l[idx] 
    if item == 2: 
     l[idx-1] 
1

我不認爲有一個簡單的方法,特別是一個迭代器可以是一個生成器(不回頭)。有一個體面的解決辦法,依靠明確地傳遞的索引,循環體:

for itemIndex, item in enumerate(l): 
    if itemIndex>0: 
     previousItem = l[itemIndex-1] 
    else: 
     previousItem = None 

enumerate()功能是內置的。

61

表示爲發電機功能:

def neighborhood(iterable): 
    iterator = iter(iterable) 
    prev_item = None 
    current_item = next(iterator) # throws StopIteration if empty. 
    for next_item in iterator: 
     yield (prev_item, current_item, next_item) 
     prev_item = current_item 
     current_item = next_item 
    yield (prev_item, current_item, None) 

用法:

for prev,item,next in neighborhood(l): 
    print prev, item, next 
+1

在這種情況下,我可能會執行「prev,item = item,next」。 – 2008-11-27 17:31:55

+1

爲了使這個循環無限(沒有StopIteration),請執行`from itertools import cycle`並將第二行更改爲:`iterator = cycle(iterable)` – 2009-12-17 01:50:04

+0

在此上下文中使用枚舉是不是Pythonic? – batbrat 2014-02-27 06:40:13

6

當你需要一些背景發生器打交道時,我經常使用下面的效用函數,在給一個滑動窗口視圖一個迭代器:

import collections, itertools 

def window(it, winsize, step=1): 
    """Sliding window iterator.""" 
    it=iter(it) # Ensure we have an iterator 
    l=collections.deque(itertools.islice(it, winsize)) 
    while 1: # Continue till StopIteration gets raised. 
     yield tuple(l) 
     for i in range(step): 
      l.append(it.next()) 
      l.popleft() 

它會生成序列N個視圖在at ime,移動步驟結束。例如。

>>> list(window([1,2,3,4,5],3)) 
[(1, 2, 3), (2, 3, 4), (3, 4, 5)] 

當先行使用/後面,你還需要與數字打交道,而不必一個一個或下一個值的情況下,你可能要墊一個合適的值序列,如無。

l= range(10) 
# Print adjacent numbers 
for cur, next in window(l + [None] ,2): 
    if next is None: print "%d is the last number." % cur 
    else: print "%d is followed by %d" % (cur,next) 
0

以前?

你的意思是以下,對吧?

previous = None 
for item in someList: 
    if item == target: break 
    previous = item 
# previous is the item before the target 

如果你想ň以前的項目,你可以用一種尺寸ň的循環隊列的做到這一點。

queue = [] 
for item in someList: 
    if item == target: break 
    queue .append(item) 
    if len(queue) > n: queue .pop(0) 
if len(queue) < n: previous = None 
previous = previous[0] 
# previous is *n* before the target 
9
l=[1,2,3] 
for i,item in enumerate(l): 
    if item==2: 
     get_previous=l[i-1] 
     print get_previous 

>>>1 
5

退房從Tempita project彎針的效用。它爲您提供圍繞項目的包裝對象,提供諸如上一個,下一個,第一個,最後一個等屬性。

查看活套類的source code,它非常簡單。還有其他這樣的循環助手,但我現在不記得任何其他人。

例子:

> easy_install Tempita 
> python 
>>> from tempita import looper 
>>> for loop, i in looper([1, 2, 3]): 
...  print loop.previous, loop.item, loop.index, loop.next, loop.first, loop.last, loop.length, loop.odd, loop.even 
... 
None 1 0 2 True False 3 True 0 
1 2 1 3 False False 3 False 1 
2 3 2 None False True 3 True 0 
-2

不是很Python的,但得到它做,很簡單:

l=[1,2,3] 
for index in range(len(l)): 
    if l[index]==2: 
     l[index-1] 

TO DO:保護邊緣

5

我知道這是舊的,但爲什麼不只是使用enumerate

l = ['adam', 'rick', 'morty', 'adam', 'billy', 'bob', 'wally', 'bob', 'jerry'] 

for i, item in enumerate(l): 
    if i == 0: 
     previous_item = None 
    else: 
     previous_item = l[i - 1] 

    if i == len(l) - 1: 
     next_item = None 
    else: 
     next_item = l[i + 1] 

    print('Previous Item:', previous_item) 
    print('Item:', item) 
    print('Next Item:', next_item) 
    print('') 

    pass 

如果你運行這個,你會看到它抓取前一個和下一個項目,並且不關心在列表中重複項目。

21

一個簡單的方法。

l=[1,2,3] 
for i,j in zip(l, l[1:]): 
    print i, j 
0

如果你想解決的iterables工作,itertools' docs有食譜,不正是你想要什麼:

import itertools 

def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    a, b = itertools.tee(iterable) 
    next(b, None) 
    return zip(a, b) 

如果你使用的是Python 2.x中,使用itertools.izip代替zip

相關問題