[Tutor] Importing file data into Python arrays

dman dman@dman.ddts.net
Tue, 28 May 2002 16:57:16 -0500


--EeQfGwPcQSOJBaQU
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, May 28, 2002 at 05:11:42PM +0100, alan.gauld@bt.com wrote:
=2E..
=20

|     nums =3D map(int,nums) # convert to integers
|     for n in nums: arr.append(n) # add to your array

Since nums and arr are both lists this can be shortened to

    arr.extend( nums ) # add to your array

| I suspect there are cleverer ways of doing this with=20
| less code but the above should be clear?

Now that you mention it, how about :

for line in f.xreadlines():
    arr.extend( [ int(n)  for n in line.strip().split() ] )

?

if you're using python 2.2 you can get away with
    for line in f :
as the first line.  (In v2.2, file objects support the iterator
protocol, and the 'for' implementation uses it)

This is an attempt to achieve compactness, not readability.  IMO it
would be better to use some temp variables and multiple lines in
production code, such as Alan presented (but use extend() rather than
the equivalent loop).

-D

--=20

Many are the plans in a man's heart,
but it is the Lord's purpose that prevails.
        Proverbs 19:21
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--EeQfGwPcQSOJBaQU
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzz/TwACgkQO8l8XBKTpRTCfgCgxvFF+StEjZ0HmVsiuKTUq/y1
lp8AnjDMd4XzEDmfakRa15/WRUiguWuI
=NeL+
-----END PGP SIGNATURE-----

--EeQfGwPcQSOJBaQU--