3 ms·
Problem with list comprehensions are that it's often not easy to see what you're trying to do. Like, I have some objects I want to group by a property, and then
by matsemann 4y ago
Problem with list comprehensions are that it's often not easy to see what you're trying to do. Like, I have some objects I want to group by a property, and then make a map containing the sum of some other property of those groups but only if it's value is above 5.
Take Kotlin:
result = myList
.filter { it.myValue > 5 }
.groupBy { it.myKey }
.mapValues { entry -> entry.value.sumOf { it.myValue }}
In python:
result = {
key: sum(el["myValue"] for el in elements)
for key, elements in groupby(
sorted([el for el in my_list if el["myValue"] > 5], key=lambda el: el["myKey"]),
key=lambda el: el["myKey"],
)
}
to me that's incomprehensible. You have to read it the wrong way, and it's not really clear what the intention behind each step is. Like, the filter is in the middle!
- gigatexal 4y agoYeah ... In that case I would write a function to return this result dict in a more imperative way in python -- but perhaps that's cuz i am not that great of an engineer/python dev. But what I can see is that the syntax of Kotlin (which I've never written) you've provided is a lot cleaner.
- jgalt212 4y agoTrue that. That's why I prefer R, and its built-in pipes, when I'm working with relatively clean data.
- js2 4y agoUse intermediate steps: keyOf = itemgetter("myKey") valueOf = itemgetter("myValue") filtered = (item for item in myList if valueOf(item) > 5) grouped = groupby(sorted(filtered, key=keyOf), keyOf) result = {key: sum(valueOf(item) for item in group) for key, group in grouped}
- gigatexal 4y agoOoh I like this. That’s about what I would do as well.
- musicale 4y agoCould you save a line by replacing valueOf(item) with item.value?
- js2 4y agoOP wrote the code as if the list items were dictionaries, so I just made that pythonic. If they are objects whose attributes we care about then we can get rid of the two getters altogether which are mostly there to make the code more legible but also remove duplication. You could also switch them to attrgetters.
- dfinninger 4y agoYeah that Python would not pass my code review. Rule of thumb is don’t nest list comprehensions, and if you have to try to keep it to two. Checkpoint the results info a variable. You aren’t supposed to chain like that in Python. From https://docs.python.org/3/tutorial/datastructures.html#id2 https://docs.python.org/3/tutorial/datastructures.html#id2 > You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. [1] This is a design principle for all mutable data structures in Python. > Footnotes > [1] Other languages may return the mutated object, which allows method chaining, such as d->insert("a")->remove("b")->sort();.