【问题标题】:Python, how to get the next item out of an array (list) in a for loop [duplicate]Python,如何在for循环中从数组(列表)中获取下一项[重复]
【发布时间】:2016-06-19 16:01:16
【问题描述】:

我有一个包含时间的数组(列表),现在我需要确定重叠时间是否在此列表中的两个连续时间之间。

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 循环中数组中的下一项)

【问题讨论】:

  • 从第二个条目开始并使用 t_vorige?
  • @percusse ty。不错的建议,我去研究那个

标签: python list


【解决方案1】:

试试这个,

duurSeq=[11,16,22,29]
for c, n in zip(duurSeq, duurSeq[1:]):
    if (verstreken_tijd > c) and (verstreken_tijd < n):
        doSomething():

请参阅Iterate a list as pair (current, next) in 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)

【讨论】:

  • 谢谢你,这个工作就像我需要的一样
【解决方案2】:

在索引而不是元素上使用 for 循环

duurSeq = [11,16,22,29]
nu = time.time()
verstreken_tijd = nu - starttijd

for t in range(len(duurSeq)-1):
   if verstreken_tijd > duurSeq[i] and verstreken_tijd < duurSeq[i+1]:
      doSomething():

【讨论】:

    【解决方案3】:

    看起来你想在 for 循环中访问数组的索引。

    for index, element in enumerate(duurSeq):
        # Use duurSeq[index] to access element at any position
    

    【讨论】:

      【解决方案4】:

      听起来你需要一些指针算法。请参阅here 以获得一个很好的例子。

      TL/DR 您可以通过告诉解释器将 sizeof(int) 向上移动 1 个块来移动到数组中的下一项。基本上取内存中的下一个整数。这只是因为您知道数组中元素的大小。

      【讨论】:

        猜你喜欢
        • 2018-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-21
        • 2023-03-03
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多