Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Nested List Comprehensions to create a matrix

I'm new to list comprehensions and would like to replicate the following code below in for loops into a nested list comprehension.

 master = []
 inner = []
 for x in range(1,8):
     inner = []
     for y in range(1,x+1):
         inner.append(str(x*y).rjust(2))

     master.append(inner)

for m in master:
    print ' '.join(m)

The output looks like this:

  1
  2  4
  3  6  9
  4  8 12 16
  5 10 15 20 25
  6 12 18 24 30 36
  7 14 21 28 35 42 49

I was thinking something like:

 test =  [  
    [str(x*y).rjust(2) for x in range(1,8)] 
    for y in range(1,x+1) 
 ] 
 for t in test:
     print ' '.join(t)

But I get a traceback error:

 Traceback (most recent call last):
 File "python", line 3, in <module>
 NameError: name 'x' is not defined

Any python experts care to point me in the right direction?

Thank you in advance!

like image 295
mba12 Avatar asked Mar 04 '16 15:03

mba12


1 Answers

You could use the following nested list comprehension:

answer = [[i*j for i in range(1, j+1)] for j in range(1, 8)]
print(answer)

Output

[[1],
 [2, 4],
 [3, 6, 9],
 [4, 8, 12, 16], 
 [5, 10, 15, 20, 25], 
 [6, 12, 18, 24, 30, 36], 
 [7, 14, 21, 28, 35, 42, 49]]
like image 63
gtlambert Avatar answered Dec 21 '22 08:12

gtlambert