What other approach can I use instead of 'lambda'
def calculate_fees(self):
return sum(map(lambda x: x.fee, self.bookings.values()))
def calculate_donations(self):
return sum(map(lambda x: x.donation, self.bookings.values()))
def __str__(self):
output = 'Event: {0} {1} {2}\n'.format(self.event_id, self.event_date, self.venue) + \
'Miles: {0}\n'.format(self.miles) + \
'Max Places: {0}\n'.format(self.max_places) + \
'Basic Fee: £{0}'.format(self.basic_fee)
if self.bookings:
output += '\nRunners:\n' + \
'\n'.join(map(lambda x: '{0} {1}'.format(x.runner_id, x.club_id), self.bookings.values()))
return output
The first occurence of lambda could be replaced with a generator:
return sum(x.fee for x in self.bookings.values())
Similar for the second:
return sum(x.donation for x in self.bookings.values())
The third:
'\n'.join('{0} {1}'.format(x.runner_id, x.club_id) for x in self.bookings.values())
Since sum and string.join can deal with a generator, you can use the generator expression directly as an argument to these functions.
Use a generator:
return sum(x.fee for x in self.bookings.values())
Generally, generators and comprehensions improve readability, especially if you have to use a lambda to make map or filter work. Moreover, map and lambda don't play well together performance-wise (Python List Comprehension Vs. Map).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With