can list comprehensions replace map?
Christopher Subich
spam.csubich+block at block.subich.spam.com
Thu Jul 28 21:53:53 EDT 2005
Andrew Dalke wrote:
> Steven Bethard wrote:
>
>>Here's one possible solution:
>>
>>py> import itertools as it
>>py> def zipfill(*lists):
>>... max_len = max(len(lst) for lst in lists)
>
>
> A limitation to this is the need to iterate over the
> lists twice, which might not be possible if one of them
> is a file iterator.
>
> Here's a clever, though not (in my opinion) elegant solution
>
> import itertools
>
> def zipfill(*seqs):
> count = [len(seqs)]
> def _forever(seq):
> for item in seq: yield item
> count[0] -= 1
> while 1: yield None
> seqs = [_forever(seq) for seq in seqs]
> while 1:
> x = [seq.next() for seq in seqs]
> if count == [0]:
> break
> yield x
I like this solution best (note, it doesn't actually use itertools). My
naive solution:
def lzip(*args):
ilist = [iter(a) for a in args]
while 1:
res = []
count = 0
for i in ilist:
try:
g = i.next()
count += 1
except StopIteration: # End of iter
g = None
res.append(g)
if count > 0: # At least one iter wasn't finished
yield tuple(res)
else: # All finished
raise StopIteration
More information about the Python-list
mailing list