[Tutor] Data structure question / PyGoogle
Python
python at venix.com
Sat Sep 16 18:12:16 CEST 2006
(forwarding to list)
On Sat, 2006-09-16 at 10:31 -0500, Brian Edward wrote:
> Thanks for the quick reply! I really appreciate your assistance. Of
> course, it will take some time to get this worked out, but your
> explanation is very clear.
>
> Best,
> Brian
>
>
> On 9/16/06, Python <python at venix.com> wrote:
> On Sat, 2006-09-16 at 09:44 -0500, Brian Edward wrote:
> > Hello all,
> >
> > I am new to Python (and programming in general) and am
> trying to get
> > PyGoogle figured out for some specific research
> interests. Basically,
> > I have done a simple search using PyGoogle and have some
> sitting in
> > memory. I have an object data.results, which is apparently
> a list:
> >
> > >>> type(data.results)
> > <type 'list'>
> >
> > In this list, I have ten URL saved, which I can access by
> using the
> > brackets and noting the specific elements. For example:
> >
> > >>> data.results[0].URL
> > 'http://www.psychguides.com/gl-
> treatment_of_schizophrenia_1999.html'
> >
> > >>> data.results [1].URL
> > 'http://www.psychguides.com/sche.pdf'
> >
> > My question is, how can I access all ten URLs in a single
> command.
> > Specifically, why does the following statement not work:
> >
> > >>> data.results[0:10].URL
> You need to extract the URL from each item in the result list.
> Something like:
>
> urls = [r.URL for r in data.results]
>
> will extract a list of urls from your list of results.
> >
> > Traceback (most recent call last):
> > File "<pyshell#78>", line 1, in -toplevel-
> > data.results[0:10].URL
> > AttributeError: 'list' object has no attribute 'URL'
> >
> >
> > Again, I am new to Python, so a watered-down, conceptual
> response to
> > this would be greatly appreciated. Thanks in advance.
>
> data.results[0:10] simply copies the first 10 results from
> your original
> list into a new list. The new list does not have a URL
> attribute, as
> the error message tells us. The URL attribute belongs to the
> individual
> items in the list.
>
> You need to process each result in data.results to extract the
> URL.
> Your choices boil down to:
> for statement
> or the more functionally oriented
> map
> list comprehension
> generator expression (python 2.4 or later)
>
> For creating a new list from an existing list, a list
> comprehension is
> usually the best bet. The for statement approach would look
> something
> like:
> urls = []
> for r in data.results:
> urls.append(r.URL)
>
> list comprehensions provide a simpler, more direct syntax.
>
>
>
> >
> > Brian
> >
> >
> >
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> --
> Lloyd Kvam
> Venix Corp
>
>
--
Lloyd Kvam
Venix Corp
More information about the Tutor
mailing list