For loop Python3:在for循环中查找上一个/下一个元素
对于Python2.x,这个问题以前已经回答过了。我无法让它在Python 3中工作For loop Python3:在for循环中查找上一个/下一个元素,for-loop,python-3.x,For Loop,Python 3.x,对于Python2.x,这个问题以前已经回答过了。我无法让它在Python 3中工作 from itertools import tee, islice, chain def previous_and_next(some_iterable): prevs, items, nexts = tee(some_iterable, 3) prevs = chain([None], prevs) nexts = chain(islice(nexts, 1, None), [Non
from itertools import tee, islice, chain
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
print(zip(prevs, items, nexts))
a = list(range(1,10))
previous_and_next(a)
我将izip
更改为zip
,因为我知道izip已从Python 3中删除
from itertools import tee, islice, chain
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
print(zip(prevs, items, nexts))
a = list(range(1,10))
previous_and_next(a)
运行此命令将为我提供
这段代码怎么了?
是一个迭代器。要获取迭代器中的项,必须将其传递给tuple()
或list()
。
具体来说,将print(zip(prevs,items,nexts))
替换为print(tuple(zip(prevs,items,nexts))
或print(list(zip(prevs,items,nexts)))