![]() |
Extract columns from a 2 dimentional table - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Extract columns from a 2 dimentional table (/thread-36463.html) |
Extract columns from a 2 dimentional table - Leyo - Feb-22-2022 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) I don't understand what to do with the parameter matcan you help me understand what's wrong with my code? I use Python 3 and Jupyter Notebook Thanks in advance, Leyo RE: Extract columns from a 2 dimentional table - DPaul - Feb-22-2022 Hi, You are making it more difficult than necessary ![]() M has 3 rows Each row has 4 columns so: for row in M... and every row [0] is the first col....etc. Paul RE: Extract columns from a 2 dimentional table - BashBedlam - Feb-22-2022 One reason for not using one and two letter variable names is that things like mat can 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)) RE: Extract columns from a 2 dimentional table - Leyo - Feb-22-2022 (Feb-22-2022, 04:06 PM)DPaul Wrote: Hi, thanks Paul ![]() RE: Extract columns from a 2 dimentional table - Leyo - Feb-22-2022 (Feb-22-2022, 06:56 PM)BashBedlam Wrote: One reason for not using one and two letter variable names is that things like |