On Wed, Sep 29, 2010 at 7:32 PM, Bruce Whealton
<br...@futurewavedesigns.com> wrote:
Hello all,
I recently started learning python. I am a bit thrown by a certain
notation that I see. I was watching a training course on lynda.com and this
notation was not presented. For lists, when would you use what appears to
be nested lists, like:
[[], [], []]
a list of lists?
Lists are for working with a group of data. Sometimes each datum
happens to itself be a list; thus, one naturally ends up with a
list-of-lists.
Say I have, for each school in my school district, a list of its
students' test scores. I want to compute each school's average score.
So I put all the lists of scores into a nested list. I then iterate
over the nested list, taking the average of each inner list of scores.
(Do the analogous thing at higher and higher levels of aggregation
(e.g. county, state, country) and you naturally get progressively more
nested lists.)
Would you, and could you combine a dictionary with a list in this fashion?
Yes, of course:
{'a' : [1,2,3]}
[{'a' : 1}, {'b' : 2}]
Just note that lists can't be dictionary keys due to their mutability.
{[1,2,3] : "one two three"} # ERROR
Next, from the documentation I see and this is just an example (this kind of
notation is seen elsewhere in the documentation:
str.count(sub[, start[, end]])
This particular example is from the string methods.
<snip>
I know that it would
suggest that some of the arguments are optional, so perhaps if there are 2
items the first is the sub, and the second is start? Or did I read that
backwards?
No, you read it exactly correctly. The []s here indicate levels of
optional-ness and have nothing to do with the list datatype.
Basically, if you want to pass an optional argument, you have to have
also specified any less-nested arguments (unless you use keyword
rather than positional arguments).
str.count(a) # sub = a
str.count(a, b) # sub = a, start = b
str.count(a, b, c) # sub = a, start = b, end = c
Usually, it's straightforward left-to-right as you specify more
arguments (doing otherwise requires kludges or black magic). However,
there are rare exceptions, the most common one being range()/xrange():
range(...)
range([start,] stop[, step]) -> list of integers
Thus:
range(a) # stop = a (*not* start = a, as would be normal)
range(a, b) # start = a, stop = b
range(a, b, c) # start = a, stop = b, step = c
Cheers,
Chris
--
http://blog.rebertia.com