[Tutor] accessing string in list

Michiel Overtoom motoom at xs4all.nl
Tue Jul 15 20:08:05 CEST 2008


Bryan wrote...

>I have a list of labels for a data file,
>test = ['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
>If I have 15.8, I would like to get the index of '20' and '15'.  I would
>also like to make sure that my known value falls in the range 4-40.

Python has a standard module 'bisect' for that. To get past the string
trouble, you could convert the array on the fly to floats (without the first
and last label, that is). Why not build your labels as a list with numbers
first, then later add the strings at the beginning and the end?  And did you
know that lists can contain both strings and numbers at the same time?

Example:


import bisect

# simple
numbers=[4, 6, 10, 15, 20, 30, 40]
candidate=15.8
print 'insert %g before the %dth element in %s' %
(candidate,bisect.bisect_left(numbers,candidate),numbers)

# complication with strings instead of numbers:
labels=['depth', '4', '6', '10', '15', '20', '30', '40', 'angle']
candidate='15.8'
can=float(candidate)
if can<4 or can>40: raise ValueError('The candidate must be in the range 4-40')
position=bisect.bisect_left([float(x) for x in labels[1:-1]],can)+1
print 'insert %s before the %dth element in %s' % (candidate,position,labels)


prints:

insert 15.8 before the 4th element in [4, 6, 10, 15, 20, 30, 40]
insert 15.8 before the 5th element in ['depth', '4', '6', '10', '15', '20',
'30', '40', 'angle']


Greetings,

-- 
"The ability of the OSS process to collect and harness
the collective IQ of thousands of individuals across
the Internet is simply amazing." - Vinod Vallopillil
http://www.catb.org/~esr/halloween/halloween4.html



More information about the Tutor mailing list