can list comprehensions replace map?

P

Peter Otten

Andrew said:
Me:
Could make it one line shorter with
from itertools import chain, izip, repeat
def fillzip(*seqs):
def done_iter(done=[len(seqs)]):
done[0] -= 1
if not done[0]:
return []
return repeat(None)
seqs = [chain(seq, done_iter()) for seq in seqs]
return izip(*seqs)

Peter Otten:
that won't work because done_iter() is now no longer a generator.
In effect you just say

seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1],
[])]

It does work - I tested it. The trick is that izip takes iter()
of the terms passed into it. iter([]) -> an empty iterator and
iter(repeat(None)) -> the repeat(None) itself.

Seems my description didn't convince you. So here's an example:
.... def done_iter(done=[len(seqs)]):
.... done[0] -= 1
.... if not done[0]:
.... return []
.... return repeat(None)
.... seqs = [chain(seq, done_iter()) for seq in seqs]
.... return izip(*seqs)
....
list(fillzip(range(6), range(3))) [(0, 0), (1, 1), (2, 2)]
versus
[(0, 0), (1, 1), (2, 2), (3, None), (4, None), (5, None)]

Now where's the typo?
'Course then the name should be changed.

My variable names where ill-chosen to begin with.

Peter
 
P

Peter Otten

Scott said:
Can I play too?

Not unless you buy the expensive but good-looking c.l.py gaming license
which is only available trough me :)
How about:
import itertools

def fillzip(*seqs):
def Nones(countactive=[len(seqs)]):
countactive[0] -= 1
while countactive[0]:
yield None
seqs = [itertools.chain(seq, Nones()) for seq in seqs]
return itertools.izip(*seqs)

You may be introducing a lot of extra tests in the while loop with the
non-constant condition -- which in practice is fairly cheap, though.
I'm willing to take the performance hit for the introduction of sane
variable names alone...

Peter
 
A

Andrew Dalke

Peter said:
Seems my description didn't convince you. So here's an example:

Got it. In my test case the longest element happened to be the last
one, which is why it didn't catch the problem.

Thanks.

Andrew
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,264
Latest member
FletcherDa

Latest Threads

Top