1

I have a list of 2D elements

m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]

and I want my output to be:

1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20

I tried this loop:

for i in range(3):
    for k in range(i,len(m),3):
        print(*m[i][k:k+3],sep='\t')

but it prints

1 2 3
4 5
6 7 8
9 10
11 12 13
14 15
16 17 18

and gives me an error

I'm not sure if it is possible since it is going on the next element. Can anyone help me on this?

BeRT2me
  • 12,699
  • 2
  • 13
  • 31
XeLa
  • 19
  • 1
  • The second half of this question (dividing into groups of three for output) distinguishes it, but there's a lot of info about the flattening part in the answers over [here](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists). – CrazyChucky Oct 18 '22 at 03:17

7 Answers7

1

You can use this snippet

m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]

flag=0

for i in range(len(m)):

    for j in range(len(m[i])):
        if(flag==3):
            print()
            flag=0
        print(m[i][j],end=" ")
        flag+=1
CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
Ajay K
  • 3
  • 4
1

An approach like this would work:

m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]

curr = 0
for i in m:
  for j in i:
    curr += 1
    if(curr % 3 == 0):
      print(j)
    else:
      print(j, end = ' ')

Output:

1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 

You can create a variable, curr, to act as a counter variable. Then, iterate through every element of m, and increment curr with each iteration. For every third element, given by curr % 3 == 0%, we print an element WITH a newline. For every not-third element, we print the element without a newline.

I hope this helped! Please let me know if you have any further questions or clarifications :)

Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
  • Instead of creating ```curr```, you can do ```for idx, j in enumerate(i)```, and ```idx``` acts the same as ```curr```. – PythonProgrammer Oct 15 '22 at 05:09
  • thats a good point! imo i think declaring `curr` separately makes the code a bit easier to follow, but yes, your method would be more efficient – Aniketh Malyala Oct 15 '22 at 05:41
1
import itertools
x = list(itertools.chain(*m))
print([x[i:i+3] for i in range(0,len(x),3)])

Of course, the above will print the whole thing as a list of lists, but you can go from there to printing each of the individual sublists.

Programmer
  • 369
  • 1
  • 10
1

I would try something like

count = 0
for arr in matrix:
    for num in arr:
        print(num, end=' ')
        count += 1
        if count == 3:
            print()
            count = 0
CSEngiNerd
  • 199
  • 6
1

one-line version:

print("".join([str(e)+" " if e%3!=0 else str(e)+"\n" for row in m for e in row]))

P.S. m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]] as that of OP.


easy-to-read version:

m does not need to be identical to that of OP. Could be any 2d matrix.

flat = [e for row in m for e in row]
for i in range(len(flat)):
    if i%3 != 2 : print(flat[i], end = " ")
    else : print(flat[i], end = "\n")
if len(flat)%3 != 0: print("") 
Xin Cheng
  • 1,432
  • 10
  • 17
0

itertools.chain combines all the sublists, and more_itertools.chunked breaks that up into equal-sized segments.

from itertools import chain
from more_itertools import chunked

m = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]]

for triplet in chunked(chain(*m), 3):
    print(*triplet)
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20

(The asterisks are for unpacking; in this case print(*triplet) is effectively the same as print(triplet[0], triplet[1], triplet[2]), and print automatically inserts a space between multiple arguments by default.)

P.S. Nine times out of ten, if you're mucking about with indexes in a Python loop, you don't need to.

CrazyChucky
  • 3,263
  • 4
  • 11
  • 25
0

It has multiple ways to do that but easiest way is one line approaching using list comprrehension. flat = [element for sublist in m for element in sublist]

m = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20]]
flat = [element for sublist in m for element in sublist]
print("Original list", m)
print("Flattened list", flat)
Mehmaam
  • 573
  • 7
  • 22
  • 1
    I believe this is the shortest and most efficient solution in native python. ```itertools``` would obviously be faster, but for someone who doesn't want to dabble into too many modules, this is great! – PythonProgrammer Oct 15 '22 at 12:48
  • You still need to spit it up into threes, though. If this question were *only* about flattening, it would be a [duplicate](https://stackoverflow.com/questions/952914/how-do-i-make-a-flat-list-out-of-a-list-of-lists). – CrazyChucky Oct 18 '22 at 03:15