Re:Python iteration
by MaxGabriel on Wednesday April 25, 2012 @03:36PM
(#3890633)
Can you control the ordering of map/filter/reduce? As in, I want to iterate through a matrix by iterating through the columns and rows in reverse order? As in:
I've just started using map/filter/reduce so I'm not sure.
[ Parent
| on HN ]
No. They start from the beginning and go to the end. Conceptually it could work on any iterable, and not just a list container.
You can, however, use the 'reversed()' function, as in "for row in reversed(rows): for col in reversed(row): print col"
There is a special double-underscore method, which lists and other data structures support, to allow iteration in reverse with the normal performance of forward iteration.
What data structure are you using to represent your matrix? A list of lists? If so, it's not terribly difficult:
>>> a = [[1,2,3], [4,5,6], [7,8,9]]
>>> b = zip(*map(reversed, reversed(a))
>>> b
[(9, 6, 3), (8, 5, 2), (7, 4, 1)]
>>> reduce(operator.add, b) # could also use a lambda with + instead of operator.add...
(9, 6, 3, 8, 5, 2, 7, 4, 1)