2008-11-27 104 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

相关问题