List comprehension for loops Python

2019-03-12 00:22发布

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

5条回答
Animai°情兽
2楼-- · 2019-03-12 00:41

Another possibility is:

for x,y in ((x,y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y):
  print (x, y, x * y)

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..

查看更多
3楼-- · 2019-03-12 00:42

Use numpy. This lets you use arrays that add up like vectors:

x = numpy.arange(3)
y = numpy.arange(3)
total = x + y

With the modified question, add a call to sum as well

total = numpy.sum(x+y)
查看更多
倾城 Initia
4楼-- · 2019-03-12 00:46

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.

查看更多
\"骚年 ilove
5楼-- · 2019-03-12 00:51

sum works here:

total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y)
查看更多
孤傲高冷的网名
6楼-- · 2019-03-12 00:51

Reduce function directly reduces collective items to single item. You can read more about them here, but this should work for you:

total=reduce(lambda x,y:x+y,range(4))

or

total=reduce(lambda x,y:x+y,(0,1,2,3))
查看更多
登录 后发表回答