3

I want to create a List from a List of Lists in Python. This is my approach

    grid=[[0,1,1], \
          [1,0,1], \
          [1,1,1], \
          [1,0,0]]
    grid2=[]
    for x in range(0,len(grid)):
     for y in range(0,len(grid[x])):
       if grid[x][y]==0:
         grid2.append(22)
       if grid[x][y]==1:
         grid2.append(44)

    for item in grid2:print grid2

The output that I expected is in grid2 the list will be like this:

22,44,44
44,22,44
44,44,44
44,22,22

But it seems my logic is wrong. Need some help

oxvoxic
  • 325
  • 2
  • 4
  • 19

5 Answers5

1

Your print loop is wrong. As written, you print grid2 in its entirety for every item in grid2. You can fix it by printing item instead.

for item in grid2: print item

If you want to instead print the exact output that you specified in the question, while keeping a 1D list, you can borrow some code from this answer and use ",".join.

def chunks(l, n):
    """ Yield successive n-sized chunks from l.
    """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]


for item in chunks(grid2, 3): print ",".join(str(x) for x in item)

Output:

22,44,44
44,22,44
44,44,44
44,22,22
Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
1

You need to treat grid2 as a list of lists. At least that's what I think you are trying to do.

grid=[[0,1,1], \
      [1,0,1], \
      [1,1,1], \
      [1,0,0]]
grid2=[]
for x in range(0,len(grid)):
    grid2.append([])
    for y in range(0,len(grid[x])):
        if grid[x][y]==0:
           grid2[x].append(22)
        if grid[x][y]==1:
           grid2[x].append(44)

for item in grid2:
    print ','.join([str(x) for x in item])
woot
  • 7,406
  • 2
  • 36
  • 55
  • Also, I'm not saying this is the best way to do this, I am just assuming you are learning the language so showing how to fix your code is probably best. – woot May 18 '14 at 01:26
0

Your print loop is wrong.

for item in grid2:
    print (item)

You can have a much better solution using numpy:

a = np.array([[0,1,1],
      [1,0,1],
      [1,1,1],
      [1,0,0]])
np.where(a == 0, 22, 44)
Out[23]: 
array([[22, 44, 44],
       [44, 22, 44],
       [44, 44, 44],
       [44, 22, 22]])
Ankur Ankan
  • 2,953
  • 2
  • 23
  • 38
0

You should replace for item in grid2:print grid2 with for item in grid2:print item (for each item you print the entire list)

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
0

Try this:

grid=[[0,1,1], \
  [1,0,1], \
  [1,1,1], \
  [1,0,0]]

grid2=[",".join(["44" if flag else "22" for flag in row]) for row in grid]
print "\n".join(grid2)
Josip Grggurica
  • 421
  • 4
  • 12