0

I'm trying to create this program (in python) that converts all rows to columns and columns to rows.

To be more specific, the first input are 2 numbers. N and M. N - total rows,M total columns. I've used b=map(int, raw_input().split()). and then based on b[0], Each of the next N lines will contain M space separated integers. For example:

Input:

3 5
13 4 8 14 1
9 6 3 7 21
5 12 17 9 3  

Now the program will store it in a 2D array:

arr=[[13, 4, 8, 14, 1], [9, 6, 3, 7, 21], [5, 12, 17, 9, 3]]

What's required for the output is to print M lines each containing N space separated integers. For example:

Output:

13 9 5
4 6 12
8 3 17
14 7 9
1 21 3

This is what I've tried so far:

 #Getting N and M from input
 NM=map(int, raw_input().split())
 arr=[]

 for i in xrange(NM[0]):
     c=map(int, raw_input().split())
     arr.append(c)

I've created a 2D array and got the values from input but I don't know the rest. Let me make this clear that I'm definitely NOT asking for code. Just exactly what to do to convert rows to columns and in reverse.

Thanks in advance!

0

1 Answer 1

7

You can use zip to transpose the data:

arr = [[13, 4, 8, 14, 1], [9, 6, 3, 7, 21], [5, 12, 17, 9, 3]]
new_arr = zip(*arr)
# [(13, 9, 5), (4, 6, 12), (8, 3, 17), (14, 7, 9), (1, 21, 3)]
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much! Is there any other way to do it not using built-in functions?
for j in range(len(arr[0])): print(" ".join(str(i[j]) for i in arr)) will print exactly what you want
@RUser98 Why would you not wanna use built-ins? The traditional way is to loop through, But hey, If you wanna re-invent the wheel, you might just end up with a flat tyre!
it returns a list of tuples not a list of lists

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.