【问题标题】:Loop through array as four elements but in a consecutive fashion循环遍历数组作为四个元素,但以连续的方式
【发布时间】:2019-06-06 16:58:16
【问题描述】:

我使用下面的代码循环遍历一个数组。

arr = [1 ,2 ,3 ,4 ,5 , 6,7]
    for a, b, c in zip(*[iter(arr)]*3):
        print (a, b, c)

它以 (1,2,3) 和 (4,5,6) 两部分检索输出

但是我希望输出在意义上是连续的 (1,2,3),(2,3,4),(3,4,5),(4,5,6),(5,6 ,7) 但也以更快的方式。 除了 iter 还有其他方法可以实现吗?

【问题讨论】:

标签: python loops for-loop iteration


【解决方案1】:

只使用切片:

>>> l = list(range(10))
>>> list(zip(l, l[1:], l[2:]))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]

如果你使用itertools.islice会更好

>>> from itertools import islice
>>> list(zip(l, islice(l, 1, None), islice(l, 2, None)))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]

【讨论】:

    【解决方案2】:

    您还可以循环大小为n的切片

    n = 3
    for a, b, c in [arr[i:i+n] for i in range(len(arr)-(n-1))]:
        print(a, b, c)
    #1 2 3
    #2 3 4
    #3 4 5
    #4 5 6
    #5 6 7
    

    【讨论】:

      【解决方案3】:
      from toolz.itertoolz import sliding_window
      arr = [1 ,2 ,3 ,4 ,5 , 6,7]
      list(sliding_window(3,arr))
      

      输出

      [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]
      

      【讨论】:

        猜你喜欢
        • 2019-01-20
        • 2015-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-06
        • 1970-01-01
        • 2012-07-27
        相关资源
        最近更新 更多