迭代增加步骤

时间:2014-11-18 22:37:30

标签: python

我试图以增加的步骤迭代元素列表(假设我们不知道列表的长度)。 具体来说:在第一次迭代过程中2 ^ 1个元素,在第二步过程2 ^ 2。因此,每个第i轮将处理2 ** i个元素。

我设法让它运转起来:

tmp = iter(A)
i = 0
no_inserted = 0 
while True:
for elm in tmp:
    print i,elm
    no_inserted = no_inserted + 1
    if no_inserted == 2**i:
        i = i +1
        print "New round"
else:
    break

但不知怎的,它看起来并不合适。有没有更好的方法在python中做到这一点?

2 个答案:

答案 0 :(得分:0)

也许这就是你想要的?

def iter_incr(l, base):
    limit = base
    while limit <= len(l) + (base-1):
        yield l[:limit]
        limit += base


tmp = [1,2,3,4,5,6,7,8,9]

for res in iter_incr(tmp, 2):
    print(res)

# Results:
[1, 2]
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

答案 1 :(得分:0)

我想我误解了你想要的东西。以下可能会更有意义。

def gen_slice(xs, low=0, step=1, high=None):
    """
    >>> xs = gen_slice(range(1, 10), 1)
    >>> list(next(xs))
    [1]
    >>> list(next(xs))
    [1, 2]
    >>> list(next(xs))
    [1, 2, 3]
    >>> list(next(xs))
    [1, 2, 3, 4]
    >>> list(next(xs))
    [1, 2, 3, 4, 5]
    >>> list(next(xs))
    [1, 2, 3, 4, 5, 6]
    >>> list(next(xs))
    [1, 2, 3, 4, 5, 6, 7]
    >>> list(next(xs))
    [1, 2, 3, 4, 5, 6, 7, 8]
    >>> list(next(xs))
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> list(next(xs))
    Traceback (most recent call last):
        ...
    StopIteration

    To start with an empty slice set the low to 0
    >>> xs = gen_slice(range(1, 10), 0)
    >>> list(next(xs))
    []

    To stop on part of the iterable rather than use all elements
    >>> xs = gen_slice(range(1, 10), 1, high=3)
    >>> list(next(xs))
    [1]
    >>> list(next(xs))
    [1, 2]
    >>> list(next(xs))
    [1, 2, 3]
    >>> list(next(xs))
    Traceback (most recent call last):
        ...
    StopIteration

    You could use the step to for bigger strides
    >>> xs = gen_slice(range(1, 10), low=0, step=2, high=4)
    >>> list(next(xs))
    []
    >>> list(next(xs))
    [1, 2]
    >>> list(next(xs))
    [1, 2, 3, 4]

    """
    high = high or len(xs)
    while True:
        yield itertools.islice(xs, 0, low)
        if low == high:
            break
        low += step