Using functional tools
Chris Emery
deathfox at moochercrew.org
Sat May 4 05:09:18 EDT 2002
This is how I might do it.
>>> list2 = [list[a] for a in range(len(list)) if not a % 2]
>>> list2
['a', 'c', 'e']
where list[a], you could replace with list[function(a)], and the
if not a % <num>, is how often you want to do it.
for the reading in of files, I belive you really don't have a choice...,
but to write, you can shorten it a bit as such
open("myfile.txt", "w").writelines([list[a] for a in range(len(list)) if
not a % 2])
or something to that affect
My $00.2
Chris
On Sat, 2002-05-04 at 01:37, Pekka Niiranen wrote:
> 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 ?
>
> 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()
> **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-
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list