-1

I have a list with lists in it.

[['H','J','K','L'],['Q','W','E','R'],['R','W','Q','T']]

I want to print the same indexes within one line with a space between them.the So output would be:

H Q R 
J W W
K E Q 
L R T

I tried using for loop using enumerate and while loop. Nothing seems to work and I'm just a beginner so I don't even know the correct way to approach this. I'd be really grateful if someone could help me out.

Thanks a lot! Have a nice day!

Ajax1234
  • 69,937
  • 8
  • 61
  • 102
Jake K
  • 15
  • 1

3 Answers3

2

You can use str.join with zip:

s = [['H', 'J', 'K', 'L'], ['Q', 'W', 'E', 'R'], ['R', 'W', 'Q', 'T']]
new_s = '\n'.join(' '.join(i) for i in zip(*s))

Output:

H Q R
J W W
K E Q
L R T
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0
'''
OP has 3 nested lists. OP wants to print each row of the list unto a line with
a space in between each line item.
'''

sample_list = [['H', 'J', 'K', 'L'], ['Q', 'W', 'E', 'R'], ['R', 'W', 'Q', 'T']]


import numpy as np

sample_array = np.array(sample_list)
print(sample_array.reshape(4, 3))

Here is the output:

[['H' 'J' 'K']
 ['L' 'Q' 'W']
 ['E' 'R' 'R']
 ['W' 'Q' 'T']]

As a beginner, it may be useful to learn about numpy. It simplifies tasks such as this when you are working with data in lists. What I did here is I created a numpy array from the nested list that you showed. numpy has a method called. reshape() that allows you to align the amount of rows and columns that you want for the data. In your example you wanted 4 rows and 3 columns for the letter, so passing 4, 3 to the .reshape() function will allow you to get 4 rows and 3 columns for the data. As a beginner, there are libraries in Python such as numpy that can help you simplify tasks such as this. I hope that this answer helps as you learn more.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27
0

For your specific case it's sufficient to do the following:

for i in range(len(list_a[0])):
    print(" ".join([l[i] for l in list_a]))

The for loop makes sure that you are getting element in the order you want and the list comprehension just gets elements from sublists at specified index and prints them in order.

Stoicas
  • 101
  • 4