On 12/7/2009 7:22 AM, Jorge Cardona wrote:
Hi,

I was trying to create a function that receive a generator and return
a list but that each elements were computed in a diferent core of my
machine. I start using islice function in order to split the job in a
way that if there is "n" cores each "i" core will compute the elements
i,i+n,i+2n,..., but islice has a weird (to me) behavior, look:

it's nothing weird, python just do what you're telling it to:

transform all x in X with f(x)
g = (f(x) for x in X)
then slice the result of that
print(list(x for x in islice(g,0,None,2)))

what you want to do is to slice before you transform:
>>> g = (x for x in islice(X, 0, None, 2))
>>> print(list(f(x) for x in g))
eval: 0
eval: 2
eval: 4
eval: 6
eval: 8
[0, 2, 4, 6, 8]

islice execute the function at the generator and drop the elements
that aren't in the slice. I found that pretty weird, the way that i
see generators is like an association between and indexing set (an
iterator or another generator) and a computation that is made indexed
by the indexing set, and islice is like a "transformation" on the
indexing set,it doesn't matter the result of the function, the slice
should act only on the indexing set, some other "transformation" like
takewhile act on the result so, the execution it has to be made, but
in the islice, or other "transformation" that act only in the indexing
set, the function shouldn't be executed at each element, but only on
that new set that result of the application of the "transformation" on
the original set.

that seems like an extremely lazy evaluation, I don't know if even a true lazy language do that. Python is a strict language, with a few laziness provided by generators, in the end it's still a strict language.

Well, it works for what i need, but is not very neat, and i think that
there it should be a formal way to act on the base indexing iterator,
such way exists? Is there a better approach to get what i need?

Reverse your operation.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to