[Tutor] casting string to integer in a list of lists
spir
denis.spir at free.fr
Thu Jan 8 22:57:52 CET 2009
Le Thu, 8 Jan 2009 11:51:01 -0800 (PST),
culpritNr1 <ig2ar-saf1 at yahoo.co.uk> a écrit :
>
> 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.
In you do not need checking whether specific items are "castable" (i.e. you really know what's in
the list) you may use such a pattern:
lol = [[1,2,3],[4,5,6],[7,8,9]]
new_lol = [[a,b**3,c] for [a,b,c] in lol]
print lol
print new_lol
==>
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 8, 3], [4, 125, 6], [7, 512, 9]]
denis
> Thank you,
>
> Your Culprit
>
>
------
la vida e estranya
More information about the Tutor
mailing list