3 ms·
And all of it is less readable than city_temps .select { |ct| ct.temp > 20 } .to_h { |ct| [ct.name, ct.temp] } Or let map: HashMap<_, _
by stouset 3y ago
And all of it is less readable than
city_temps
.select { |ct| ct.temp > 20 }
.to_h { |ct| [ct.name, ct.temp] }
Or
let map: HashMap<_, _> = city_temps
.iter()
.filter(|ct| ct.temp > 20 )
.map(|ct| (ct.name, ct.temp) )
.collect();
- ReleaseCandidat 3y agoThere is no need to use anything but filter, like filtered_temps = list(filter(lambda e: e["temp"] > 20, temperatures)) IMHO the most readable version (and coincidentally also the shortest).
- stouset 3y agoIn the provided example, they’re turning it into a map of city names to temps so I kept that. Yours keeps it as an array of objects with a name and temp. If you skip that, city_temps .select { |ct| ct.temp > 20 } city_temps .iter() .filter(|ct| ct.temp > 20 ) .collect(); are still best IMO just due to the natural method chaining of iterators.
- ReleaseCandidat 3y agoOh, yes, of course you're right, I didn't see that until now - did I say already, that I hate Python's list comprehensions or everything not totally simple?. So that needs reduce: def filter_func(acc, e): if e["temp"] > 20: acc[e["city"]] = e["temp"] return acc filtered_temps = functools.reduce(filter_func, temperatures, {})
- Izkata 3y agoTechnically that's a dict comprehension, not a list comprehension (though they are pretty much the same). The old style, before they existed, was to create a list of 2-tuples (key/value pairs) in a list comprehension and pass that to dict().