[Tutor] Using lists as table-like structure
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Wed Nov 16 23:19:49 CET 2005
On Wed, 16 Nov 2005, Bernard Lebel wrote:
> Let say I have a list of lists. Each individual lists have a bunch of
> elements. Now I would like to either get or set the first element of
> each individual list. I could do a loop and/or list comprehension, but I
> was wondering if it was possible with something like:
>
> aList = [ [1,1,1], [2,2,2,], [3,3,3] ]
> aList[:][0] = 10
Hi Bernard,
I think I see what you're trying to do; you're trying to clear the first
column of each row in your matrix. Unfortunately, this is not done so
easily in standard Python. However, if you use the third-party Numeric
Python (numarray) package, you can use its array type to do what you want.
> If I print aList[:], I get the list with the nested sublists.
>
> >>> aList[:]
> [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
Yes, sounds good so far.
> But as soon as I introduce the [0], in an attempt to access the first
> element of each sublist, I get the first sublist in its entirety:
>
> >>> aList[:][0]
> [1, 1, 1]
Let's do a quick substitution model thing here. You mentioned earlier
that:
> >>> aList[:]
> [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
So if we just plug that value into aList[:][0]:
aList[:][0] ==> [[1, 1, 1,], [2, 2, 2], [3, 3, 3]] [0]
then we see that we're just asking for the first element of aList[:],
which is [1, 1, 1].
> I would have hoped to get something like [1, 2, 3]
Take a look into Numeric Python: it'll give you the row/column slicing
operations that you're expecting. As a concrete example:
######
>>> import numarray
>>> a = numarray.array([[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]])
>>> a[:, 0]
array([1, 4, 7])
>>> a[:, 1]
array([2, 5, 8])
>>> a[:, 2]
array([3, 6, 9])
######
Best of wishes!
More information about the Tutor
mailing list