Newbie: searching a list

Rainy sill at optonline.net
Wed May 23 13:02:53 EDT 2001


On Wed, 23 May 2001 11:18:53 -0500, user <user at comm.mot.com> wrote:
> I have a list generated from a "sentence=split(some_file.readline())"
> statement.
> 
> A sample list resulting from this statement is:
>     ['Independent', 'Variable', '=', '11', ';']
> 
> I want to extract the '11', which is the next item in the list following
> the equals sign; I thought to get it this way:
> 
> found=0
> IV=''
> for item in sentence:
>     if found:
>         IV=item
>         break
>     if item == "=":
>         found=1
> 
> This works, but is it the best way to do it?
> 
> -- Stephen
> 

Is it always the 4th one there?

If so, you may do something like

var = sentence[3]

If not, but if it's the first int there, you may do this:

for item in sentence:
    try:
        var = int(item)
    except ValueError: pass
    else: break

If not, you can do this:

indOfEq = sentence.index('=')
var = sentence[indOfEq+1]

Actually, this seems to be the easiest and
most safe (and clear) way..

-- 
I'll give you anything, everything if you want things
        - Syd



More information about the Python-list mailing list