Select column from a list
Dave Angel
davea at ieee.org
Fri Aug 28 14:35:35 EDT 2009
hoffik wrote:
> Hello,
>
> I'm quite new in Python and I have one question. I have a 2D matrix of
> values stored in list (3 columns, many rows). I wonder if I can select one
> column without having to go through the list with 'for' command.
>
> For example I have list called 'values'.
> When I write 'values[0]' or 'values[0][:]' I'll get the first row.
> But when I write 'values[:][0]' I won't get the first column, but the first
> row again! I can't see why.
>
> Thanks
> Hoffik
>
Python doesn't have 2d matrices as a native type. Others have already
suggested Numpy. But I'll assume you really want to stick with what's
included in base Python, because you're still learning. (Aren't we all?)
The real question to me is how this data is related to each other. If
it's uniform data, organized in a 3x20 rectangle, or whatever, then
maybe you want to use a single list, and just use slicing to extract
particular rows and columns. You were actually using slicing in your
example above; that's what the colon does. But in your case, you used
defaults for the 3 arguments, so you got a *copy* of the entire list.
Slicing to get one row would be simply values[row*3:(row+1)*3], and
one column would be print values[column: -1: 3]
Notice that I hardcoded the width of our "matrix," since list doesn't
know anything about it. And notice it's easy to add more rows, but not
easy to change row size, because that's not part of the structure, but
part of the code to access it.
Next possibility is to make a class to describe the data structure. You
can make methods that mimic the behavior you want.
But I suspect that the row is 3 specific values, maybe not even the same
type as each other. So they might be name, address, and phone number.
Each row represents a family, and each column represents a type of
data. In this case, I'd suggest making each row an instance of a new
class you define, and making a list of those objects.
Now, you might be representing a row by an object of your class. And
representing a column by two things: your list & an accessor method
that knows how to extract that particular field.
DaveA
More information about the Python-list
mailing list