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
Another possibility is:
In this way you can iterate over anything you'd use in a list comprehension without actually creating the comprehended list (if you get my meaning ;) If comprehended list is big, maybe so big it saturates or even doesn't fit in memory, that's quite handy..
Use numpy. This lets you use arrays that add up like vectors:
With the modified question, add a call to
sum
as wellAs an alternative to writing loops N levels deep, you could use
itertools.product()
:This extends naturally to N dimensions.
sum
works here:Reduce function directly reduces collective items to single item. You can read more about them here, but this should work for you:
or