[Tutor] Data structure question / PyGoogle
Alan Gauld
alan.gauld at btinternet.com
Sat Sep 16 17:18:44 CEST 2006
> 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'
> 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
The list slice returns another list. And as the error says lists do
not have a URL attribute. You can either write a loop to return
the URLs
urls = []
for url in data.results:
urls.append(url.URL)
or more Pythonically use a List Comprehension, which
combines all of that in one line:
urls = [url.URL for url in data.results]
In general when you want to convert a list of something
to another list of something, either a subset of the original
or a transformed version, like here, use a list comprehension.
newlist = [f(x) for x in oldlist <if condition>]
> Again, I am new to Python, so a watered-down, conceptual response to
> this
> would be greatly appreciated. Thanks in advance.
You can find more on list comrehensions in the functional
programming topic of my tutor - about half way down the page...
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list