[Baypiggies] Preserving integers when loading a file into a list

Jason Culverhouse jason at mischievous.org
Sun Jun 15 21:31:54 CEST 2008


not x.isdigit() and x or int(x) is going to fail for empty string... ''
	not False and '' or int('') <-value error since

You could combine Adam's try_int_convert

import csv
import functools
import sys

i = functools.partial(map, try_int_convert) # maybe  convert a list to  
int
t = functools.partial(tuple) # convert to tuple, not sure if you need  
the in tuples

#Read a TSV file from stdin and convert
[t(i(line)) for line in csv.reader(sys.stdin, dialect='excel-tab')]

Jason

On Jun 15, 2008, at 11:43 AM, Brent Pedersen wrote:

> hi, you can use the isdigit() method on a string.
>
> $ cat stuff.txt
> 1 a 2
> b b b
> a 2 4
> 0 0 0
>
>
>>>> for line in open('stuff.txt'):
> ...       [not x.isdigit() and x or int(x) for x in  
> line.strip().split()]
> [1, 'a', 2]
> ['b', 'b', 'b']
> ['a', 2, 4]
> [0, 0, 0]
>
>
>
>
> 2 4 c
>
> On Sun, Jun 15, 2008 at 11:09 AM, Al Nevarez <anevare2 at yahoo.com>  
> wrote:
>> Hello,
>> What's the best way to preserve integers when loading a file into a  
>> list?
>>
>> for example.. assume we have a tab delimited file that looks like  
>> this:
>> A       1
>> B       2
>> C       three
>>
>> I have a line in my program to read that file in like this:
>>
>> my_data=[line.strip().split('   ') for line in file(data_file,'rU')]
>>
>> the result in my_data is:
>> [['A', '1'], ['B','2'], ['C','three']]
>>
>> But I need my_data to be like this:
>> [['A', 1], ['B',2], ['C','three']]
>>
>> Needs to be automatic.. i.e. I'm not sure ahead of time, which if  
>> any value anywhere will be a string or an integer.
>>
>> Thanks!
>> Al
>>
>>
>>
>> _______________________________________________
>> Baypiggies mailing list
>> Baypiggies at python.org
>> To change your subscription options or unsubscribe:
>> http://mail.python.org/mailman/listinfo/baypiggies
>>
> _______________________________________________
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
> http://mail.python.org/mailman/listinfo/baypiggies

-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2425 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/baypiggies/attachments/20080615/3a1fa47a/attachment.bin>


More information about the Baypiggies mailing list