[Tutor] casting string to integer in a list of lists

Marc Tompkins marc.tompkins at gmail.com
Thu Jan 8 22:26:28 CET 2009


On Thu, Jan 8, 2009 at 11:51 AM, culpritNr1 <ig2ar-saf1 at yahoo.co.uk> wrote:

>
> Hi All,
>
> Say I have this nice list of lists:
>
> LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'],
>             ['chrX', '161109992', '161109993', 'rs13484104', '63.60'],
>             ['chrX', '161414112', '161414113', 'rs13484105', '63.60'],
>             ['chrX', '161544071', '161544072', 'rs13484106', '63.60'],
>             ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'],
>             ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']]
>
> Now I want to cast the second and third "columns" from string to integer,
> like this
>
> LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'],
>             ['chrX', 161109992, 161109993, 'rs13484104', '63.60'],
>             ['chrX', 161414112, 161414113, 'rs13484105', '63.60'],
>             ['chrX', 161544071, 161544072, 'rs13484106', '63.60'],
>             ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'],
>             ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']]
>
> Is there any elegant way to do this? I can't assume that all lines will
> have
> the same number of elements.
>

Maybe not the most elegant way, but here's a quickie:
print(LoL)
for lstA in LoL:
    try:
        lstA[1] = int(lstA[1])
    except:
        pass
    try:
        lstA[2] = int(lstA[2])
    except:
        pass
print(LoL)

I put them in separate try/excepts in case the first one's not an integer
but the second one is.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090108/7b8b4717/attachment.htm>


More information about the Tutor mailing list