Python Forum
Extract columns from a 2 dimentional table
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extract columns from a 2 dimentional table
#1
hello everyone,

I struggle on this exercise:
define a function col(mat, j) allowing to retrieve a column of the matrix. For example col(M, 1) will return [2, 6, 10].

here's the matrix (list of list created with loops):
M = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]

so far I wrote:

def col(mat,j):
    for i in range(3):  #search lines
        for j in range(4): #search columns
            return M[:][j] #return all elements from i column
col(0,1)
Output:
[1, 2, 3, 4]
I don't understand what to do with the parameter mat
can you help me understand what's wrong with my code?

I use Python 3 and Jupyter Notebook

Thanks in advance,
Leyo
Larz60+ write Feb-22-2022, 04:56 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use BBCode tags on future posts.
Reply
#2
Hi,
You are making it more difficult than necessary Smile
M has 3 rows
Each row has 4 columns
so: for row in M...
and every row [0] is the first col....etc.
Paul
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply
#3
One reason for not using one and two letter variable names is that things likematcan be confusing. Descriptive variable names make the code much clearer and easier to work with and understand.
M = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]

def column (matrix, column_number) :
	output_column = []
	for row in matrix :
		output_column.append (row [column_number])
	return output_column

print (column (M, 1))
Reply
#4
(Feb-22-2022, 04:06 PM)DPaul Wrote: Hi,
You are making it more difficult than necessary Smile
M has 3 rows
Each row has 4 columns
so: for row in M...
and every row [0] is the first col....etc.
Paul

thanks Paul Smile
Reply
#5
(Feb-22-2022, 06:56 PM)BashBedlam Wrote: One reason for not using one and two letter variable names is that things likematcan be confusing. Descriptive variable names make the code much clearer and easier to work with and understand.
M = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]

def column (matrix, column_number) :
	output_column = []
	for row in matrix :
		output_column.append (row [column_number])
	return output_column

duly noted, thank you !

print (column (M, 1))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Table with fixed columns Mike2607 3 2,866 Nov-26-2019, 08:17 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020