Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- l = [1, 2, 3, 4]
- 1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ...
- def cycle(iterable):
- if not hasattr(cycle, 'state'):
- cycle.state = itertools.cycle(iterable)
- return cycle.next()
- >>> l = [1, 2, 3, 4]
- >>> cycle(l)
- 1
- >>> cycle(l)
- 2
- >>> cycle(l)
- 3
- >>> cycle(l)
- 4
- >>> cycle(l)
- 1
- >>> import itertools
- >>> def ncycle(iterable, n):
- ... for item in itertools.cycle(iterable):
- ... for i in range(n):
- ... yield item
- >>> a = ncycle([1,2], 2)
- >>> a.next()
- 1
- >>> a.next()
- 1
- >>> a.next()
- 2
- >>> a.next()
- 2
- >>> a.next()
- 1
- >>> a.next()
- 1
- >>> a.next()
- 2
- >>> a.next()
- 2
- import itertools
- def bicycle(iterable, repeat=1):
- for item in itertools.cycle(iterable):
- for _ in xrange(repeat):
- yield item
- c = bicycle([1,2,3,4], 2)
- print [c.next() for _ in xrange(10)]
- def cycle(iterable):
- while True:
- for item in iterable:
- yield item
- yield item
- x=[1,2,3]
- c=cycle(x)
- print [c.next() for i in range(10)] // prints out [1,1,2,2,3,3,1,1,2,2]
- iterable = [1, 2, 3, 4]
- n = 2
- while (True):
- for elem in iterable:
- for dummy in range(n):
- print elem # or call function, or whatever
- [ "%d, %d" % (i, i) for i in [1, 2, 3, 4] * 4]
- import itertools as it
- def ncycle(iterable, n=1):
- if n == 1:
- return it.cycle(iterable)
- return it.cycle(it.chain(*it.izip(*([iterable]*n))))
Add Comment
Please, Sign In to add comment