I use a lot of N dimensional arrays and it gets a pain to have to write such indented code and I know some codes can be replaced with list comprehensions and inline statements. For example:
for x in (0,1,2,3): for y in (0,1,2,3): if x < y: print (x, y, x*y)
can be replaced with:
print [(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]
But how could I change the action instead of print to do something else like:
total = x+y
So what I want to do is something like:
[(total+=x+y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]
However this doesn't work
Is there a smart way to do this rather than:
for x in (0,1,2,3): for y in (0,1,2,3): if x < y: total+=x+y
List comprehensions are also more declarative than loops, which means they're easier to read and understand. Loops require you to focus on how the list is created. You have to manually create an empty list, loop over the elements, and add each of them to the end of the list.
No, you cannot use while in a list comprehension. There is not a single while statement allowed anywhere. The only keywords you are allowed to use is a for , for a for loop.
Conclusions. List comprehensions are often not only more readable but also faster than using “for loops.” They can simplify your code, but if you put too much logic inside, they will instead become harder to read and understand.
List comprehensions are the right tool to create lists — it is nevertheless better to use list(range()). For loops are the right tool to perform computations or run functions. In any case, avoid using for loops and list comprehensions altogether: use array computations instead.
sum
works here:
total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y)
As an alternative to writing loops N levels deep, you could use itertools.product()
:
In [1]: import itertools as it In [2]: for x, y in it.product((0,1,2,3),(0,1,2,3)): ...: if x < y: ...: print x, y, x*y 0 1 0 0 2 0 0 3 0 1 2 2 1 3 3 2 3 6
This extends naturally to N dimensions.
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