Using functional tools

Gerhard Häring gerhard at bigfoot.de
Sat May 4 05:23:44 EDT 2002


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Pekka Niiranen wrote in comp.lang.python:
> I would like to feed every second (or 3rd or 4th .etc) item in a list to
> a function.

To just extract the 3rd element of a list of lists:

def f(x):
    # ...

l = [['a', 'b', 'c'], ['d', 'e', 'f']]
print [f(x[2]) for x in l]

I'm not sure if that's what you want.

> [...] If I only manipulate every second line of a file with that
> function, is there a faster way than reading the whole file into a
> list?:
> 
> list = open ("myfile.txt", "rb").readlines()

Yes, just iterate over the file:

def myTransformation(line):
    # ...

# [Open outfile]

for line in open("myfile.txt", "rb"):
    # The rstrip with parameters is only in Python CVS:
    line = myTransformation(line.rstrip("\r\n"))
    print >>outfile, line

In pre-2.2 Pythons, use xreadlines on the file object to get lazy file
reading behaviour.

> **modify every 2nd line with set of functions**
> ** write the whole list into a new file**
> 
> The size of a file is max 2Mb.

Then it won't make much of a difference on modern machines wether you
use readlines or xreadlines.

If you're trying to learn the functional stuff, you can also try to
find out what the reduce(... line in my signature does ;-)

Gerhard

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

iD8DBQE806ifeyJldYarQ8ARAi7SAJsH3fC1BOfQdxn6mp5xuFJZ3yTVUgCgiVVG
Y0Ageg/wqerTMShecD7faSw=
=t6Mw
-----END PGP SIGNATURE-----



More information about the Python-list mailing list