Using functional tools

Ken Seehof kseehof at neuralintegrator.com
Sat May 4 06:32:10 EDT 2002


Pekka Niiranen says:
> I would like to feed every second (or 3rd or 4th .etc) item in a list
> to
> a function.
> 
> list = ['a', 'b', 'c', 'd', 'e']
> 
> **some fancy map/filter -trick here**
> => list = ['a', function('b'), 'c', function('d'), 'e']
> 
> Is there a (functional) way without using for or while -structures ?

Okay, if you find obfuscation by functional programming
as entertaining as I do, try this pattern:

>>> def f(x):
...    return x*10
...
>>> n = 3
>>> a = [1,2,3,4,5,6,7,8,9]
>>> [((i+1)%n) and a[i] or f(a[i]) for i in range(len(a))]
[1, 2, 30, 4, 5, 60, 7, 8, 90]

> 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 ?:

Use file.xreadlines().  It acts like a list, but really it is
reading lines as needed, so you aren't actually reading the
whole file at once.
 
> list = open ("myfile.txt", "rb").readlines()
> **modify every 2nd line with set of functions**
> ** write the whole list into a new file**
> 
> The size of a file is max 2Mb.
> 
> -pekka- 

Performing readlines on a binary file seems, um, strange to me.

# untested code:
f_in = open("myfile.txt", "r")
f_out = open("myotherfile.txt", "w")
xlines = f_in.xreadlines()

i=0
n=2

for line in xlines:
    if (i+1)%n == 0:
        f_out.write(fnc(lines[i]))
    else 
	  f_out.write(line)

f_in.close()
f_out.close()   







More information about the Python-list mailing list