[Tutor] A couple beginner questions.
Sean 'Shaleh' Perry
shalehperry@home.com
Mon, 24 Sep 2001 22:56:09 -0700 (PDT)
On 25-Sep-2001 Eric Henry wrote:
> Hi there everyone. I decided work on a small project to sort of get my
> feet wet in python and programming in general. I've got a couple of
> quick questions for you all. First, is there a built in way to apply
> some operation to each item in a list? For example adding 2 to [1,2,3],
> and getting [3,4,5].
>
this one is straight from the tutorials.
[1,2,3] is a list in python. There are two handy functions in python for
lists:
map(func,list) -- every item in list is passed to func() as an argument this is
equivalent to 'for i in list: func(i)'
reduce(func, list) -- starting with the first two elements, pass two elements
to func and keep a cumalitive result. This is the same as 'total =
func(list[0], list[1]); for i in list[2:]: total = func(total, i)'
> Second, I need to store some information from a table. Each row has 3
> values. Somewhat like this:
>
> [1, 3, 4]
> [2, 4, 5]
> [3, 1, 1]
>
> From what I understand, a dictionary would let me assign each of those
> sets of information a key and retrieve them, but what I need to do is
> give it say 3 in the second column(the numbers aren't duplicated
> anywhere in each column) and have it return one or four. I don't know
> how clear that all was, but hopefully someone has some idea what I'm
> talking aobut.
>
Hmmm, sounds like a homework problem (-: Consider making the middle element
the key and the each list the data. So dict[3] -> [1,3,4]. Of course this
only works when the keys are not dups.