can list comprehensions replace map?

Andrew Dalke dalke at dalkescientific.com
Thu Jul 28 05:01:09 EDT 2005


Me:
> Here's a clever, though not (in my opinion) elegant solution
 ...
> This seems a bit more elegant, though the "replace" dictionary is
> still a bit of a hack

Here's the direct approach without using itertools.  Each list is
iterated over only once.  No test against a sequence element is ever
made (either as == or 'is') and the end of the sequence exception
is raised only once per input iterator.

The use of a list for the flag is a bit of a hack.  If the list has
1 element then its true, no elements then its false.  By doing it this
way I don't need one extra array and one extra indexing/enumeration.

def zipfill(*seqs):
    count = len(seqs)
    seq_info = [(iter(seq), [1]) for seq in seqs]
    while 1:
        fields = []
        for seq, has_data in seq_info:
            if has_data:
                try:
                    fields.append(seq.next())
                except StopIteration:
                    fields.append(None)
                    del has_data[:]
                    count -= 1
            else:
                fields.append(None)
        if count:
            yield fields
        else:
            break


Hmm, it should probably yield tuple(fields)

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list