简体   繁体   中英

print a list in a square pattern [python]

I am trying to print a list, for example:

x = [ [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9],
      [10, 11, 12]]

in a certain pattern like below:

1 2 3
4 5 6
7 8 9
10 11 12

but I couldn't figure it out.

In Java a simple nested for loop will do the job but not in Python. This is what I tried:

for i in range(0, 4):
    for j in range(0, 3):
        print(x[i][j])

But this just prints each number in a new line.

The print function has some useful extra arguments. So:

You can either print each cell with an empty end and add a new line after each row:

for row in x:
    for cell in row:
        print(cell, end=" ")
    print()

Or, print each line with an empty sep :

for row in x:
    print(*row, sep=" ")

Or finally use the join method to combine all rows:

print('\n'.join(' '.join(str(cell) for cell in row) for row in x))

print() takes an optional parameter end :

for i in range(0, 4):
    for j in range(0, 3):
        print(x[i][j], end=" ")
    print()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM