Easy question
Kalle Svensson
kalle at gnupung.net
Wed Apr 11 17:49:08 EDT 2001
Sez Brian Quinlan:
> How about something like this:
>
> # No testing, of course
> myList = []
> file = open( 'testfile', 'r' )
>
> for i in file.readlines( ):
> myList.append( [int(j.strip( )) for j in i.split('\t')] )
The j.strip() is unnecessary, int() does that automagically, IIRC.
Also, this will blow up if there is a tab at the end of the line:
>>> i = "1\t1\t0\t0\t"
>>> [int(j.strip( )) for j in i.split('\t')]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int():
>>>
I would change the list comprehension to
[int(j) for j in i.split()]
or
[int(j) for j in i.strip().split('\t')]
and perhaps add an
if i.strip():
to check for empty lines.
Otherwise, this is how I would do it too.
Peace,
Kalle
--
Email: kalle at gnupung.net | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD
[ Not signed due to lossage. Blame Microsoft Outlook Express. ]
More information about the Python-list
mailing list