Python 如何在for循环中从数组(列表)中获取下一个项目[重复]
我有一个带有时间的数组(列表),现在我需要确定该Eclipse的时间是否在此列表的两个连续时间之间。
duurSeq=[11,16,22,29]
nu = time.time()
verstreken_tijd = nu - starttijd
for t in duurSeq:
if (verstreken_tijd > t ) and (verstreken_tijd < **t_next** ):
doSomething():
我的问题是:如何获取t_next(for循环中数组中的下一项)
解决方案
duurSeq=[11,16,22,29]
for c, n in zip(duurSeq, duurSeq[1:]):
if (verstreken_tijd > c) and (verstreken_tijd < n):
doSomething():
请参阅Python中的成对列表(当前,下一个)进行迭代,以了解一般方法。
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
# Demo
l = [11, 16, 22, 29]
for c, n in pairwise(l):
print(c, n)
# Output
(11, 16)
(16, 22)
(22, 29)

浙公网安备 33010602011771号