Reputation: 15656
What I have:
array = original_array[:]
result = reduce(lambda a,b: some_function(b,array), array)
What I want:
I want to get rid of the array = original_array[:] statement. Ideally I would simply replace the array parameter inside reduce() with original_array[:], but I need it inside lambda as well. Is there a way to refer to the array parameter from within lambda?
The following is not an acceptable solution, because it makes a new array copy for every element:
result = reduce(lambda a,b: some_function(b,original_array[:]), original_array[:])
I need something like this:
result = reduce(lambda a,b: some_function(b,reduce_parameter), original_array[:])
Upvotes: 3
Views: 126
Reputation: 5149
You could wrap the whole thing in another lambda:
result = (lambda array: reduce(lambda a,b: some_function(b,array), array))(original_array[:])
But your original solution is in my opinion preferable because it's more readable.
Upvotes: 6
Reputation: 97601
Here's a way to remove that outer lambda
result = reduce(lambda a,b,array=array[:]: some_function(b,array), array)
edit: Whoops, misread the question
This of course assumes you actually need to copy the array, and that it isn't sufficient to use
result = reduce(lambda a,b: some_function(b, array), array)
Also, this is an incorrect use of reduce - you're not using the a
argument, so result
holds some_function(array[-1], array)
Upvotes: 2
Reputation: 1964
Try:
result = reduce(lambda a,b, array=array: some_function(b,array), array)
Upvotes: 0