3 ms·
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:
by MaxGabriel 14y ago
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:
[9,6,3]
[8,5,2]
[7,4,1]
I've just started using map/filter/reduce so I'm not sure.
- kisielk 14y agoWhat 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)
- dalke 14y agoNo. 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.