iterator - An elegant and fast way to consecutively iterate over two or more containers in Python? -


i have 3 collection.deques , need iterate on each of them , perform same action:

for obj in deque1:       some_action(obj)    obj in deque2:       some_action(obj)  obj in deque3:       some_action(obj) 

i'm looking function xxx ideally allow me write:

for obj in xxx(deque1, deque2, deque3):       some_action(obj) 

the important thing here xxx have efficient enough - without making copy or silently using range(), etc. expecting find in built-in functions, found nothing similar far.

is there such thing in python or have write function myself?

depending on order want process items:

import itertools  items in itertools.izip(deque1, deque2, deque3):     item in items:         some_action(item)  item in itertools.chain(deque1, deque2, deque3):     some_action(item) 

i'd recommend doing avoid hard-coding actual deques or number of deques:

deques = [deque1, deque2, deque3] item in itertools.chain(*deques):     some_action(item) 

to demonstrate difference in order of above methods:

>>> = range(5) >>> b = range(5) >>> c = range(5) >>> d = [a, b, c] >>> >>> items in itertools.izip(*d): ...     item in items: ...         print item, ... 0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 >>> >>> item in itertools.chain(*d): ...     print item, ... 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 >>> 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -