python的迭代方式_在python中以列表(循环方式)迭代对

这个无限循环,不管是好是坏,但在算法上非常清楚。

from itertools import tee, cycle

def nextn(iterable,n=2):

''' generator that yields a tuple of the next n items in iterable.

This generator cycles infinitely '''

cycled = cycle(iterable)

gens = tee(cycled,n)

# advance the iterators, this is O(n^2)

for (ii,g) in zip(xrange(n),gens):

for jj in xrange(ii):

gens[ii].next()

while True:

yield tuple([x.next() for x in gens])

def test():

data = ((range(10),2),

(range(5),3),

(list("abcdef"),4),)

for (iterable, n) in data:

gen = nextn(iterable,n)

for j in range(len(iterable)+n):

print gen.next()

test()

给予:

(0, 1)

(1, 2)

(2, 3)

(3, 4)

(4, 5)

(5, 6)

(6, 7)

(7, 8)

(8, 9)

(9, 0)

(0, 1)

(1, 2)

(0, 1, 2)

(1, 2, 3)

(2, 3, 4)

(3, 4, 0)

(4, 0, 1)

(0, 1, 2)

(1, 2, 3)

(2, 3, 4)

('a', 'b', 'c', 'd')

('b', 'c', 'd', 'e')

('c', 'd', 'e', 'f')

('d', 'e', 'f', 'a')

('e', 'f', 'a', 'b')

('f', 'a', 'b', 'c')

('a', 'b', 'c', 'd')

('b', 'c', 'd', 'e')

('c', 'd', 'e', 'f')

('d', 'e', 'f', 'a')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值