0

Here is my basic code:

import numpy as np
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])

I want to print the arrays as follows:

1 4 7
2 5 8
3 6 9

Also, how would I approach the same concept if my a array has 1000 embedded list in it?

3
  • Have you tried writing one or two loops? Commented Jun 2, 2021 at 20:50
  • @mkrieger1 Trying to think how to do two loops. Any hints? Commented Jun 2, 2021 at 20:53
  • For each column: print each column separated by line breaks; For each row in every column: print each value separated by spaces Commented Jun 2, 2021 at 20:56

2 Answers 2

1

Here is a powerful one-line solution without loops:

print('\n'.join(map(lambda line: ' '.join(map(str, line)), a.T)))

a.T transpose the 2D array, the first map encode a line in a string and the second one concatenate the string lines (by using \n between).

This is an alternative version with generators (likely slower):

print('\n'.join(' '.join(str(item) for item in line) for line in a.T))

Yet another solution with one loop (likely even slower):

for line in a.T:
    print(' '.join(str(item) for item in line))

Note the last version produce a trailing new line.

Sign up to request clarification or add additional context in comments.

2 Comments

Richard can you show how to do it in a loop as well please?
@user8607309 I edited the question to include that.
0

You could also make use of str:

print(str(a.T).translate(str.maketrans({'[':'',']':''})))
1 4 7
 2 5 8
 3 6 9

print(str(a.T).replace('[', '').replace(']',''))
1 4 7
 2 5 8
 3 6 9
print(str(a.T).translate(str.maketrans({'[':'',']':''})).replace('\n ', '\n'))
 1 4 7
 2 5 8
 3 6 9

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.