I'm currently learning Python (coming from other languages like JavaScript and Ruby). I am very used to chaining a bunch of transformations / filters, but I'm pretty sure that's not the right way to do it in Python: filter
takes a lambda before the enumerable, so writing a long / multi-line function looks really weird and chaining them means putting them in reverse order which isn't readable.
What would be the "Python way" of writing the maps and filters in this JavaScript function?
let is_in_stock = function() /* ... */ let as_item = function() /* ... */ let low_weight_items = shop.inventory .map(as_item) .filter(is_in_stock) .filter(item => item.weight < 1000) .map(item => { if (item.type == "cake") { let catalog_item = retrieve_catalog_item(item.id); return { id: item.id, weight: item.weight, barcode: catalog_item.barcode }; } else { return default_transformer(item); } });
I understand that I might use a list comprehension for the first map and the next two filters, but I am not sure how to do the last map and how to put everything together.
Thank you!
map(), filter() and reduce() work in the same way: They each accept a function and a sequence of elements and return the result of applying the received function to each element in the sequence.
The map function performs a transformation on each item in an iterable, returning a lazy iterable back. The filter function filters down items in an iterable, returning a lazy iterable back.
Anonymous Functions The functions map(), filter(), and reduce() all do the same thing: They each take a function and a list of elements, and then return the result of applying the function to each element in the list. As previously stated, Python has built-in functions like map(), filter(), and reduce().
If you don't mind using a package, this is another way to do it using https://github.com/EntilZha/PyFunctional
from functional import seq def as_item(x): # Implementation here return x def is_in_stock(x): # Implementation return True def transform(item): if item.type == "cake": catalog_item = retrieve_catalog_item(item.id); return { 'id': item.id, 'weight': item.weight, 'barcode': catalog_item.barcode } else: return default_transformer(item) low_weight_items = seq(inventory)\ .map(as_item)\ .filter(is_in_stock)\ .filter(lambda item: item.weight < 1000)\ .map(transformer)
As mentioned earlier, python lets you use lamdba expressions, but they aren't flexible as clojures in javascript since they can't have more than one statement. Another annoying python thing are the need for backslashes. That being said, I think the above most closely mirrors what you originally posted.
Disclaimer: I am the author of the above package
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