Questions about nested for's vs map

Greg Ewing greg.ewing at compaq.com
Wed Oct 27 04:57:04 EDT 1999


Felix Thibault wrote:
> 
> I've been trying to move from building the arbitrarily deeply nested
> for's to
> something using map, but so far I haven't gotten it to work. Is there a
> standard
> way to do this, or another, better way to do the same thing ?

Here is a set of recursive functions which achieves the same
result without the need to generate code:

def build(key_sequences):
    """Top level function to start everything off."""
    result = []
    build_dicts((), key_sequences, 0, result)
    return result
    
def build_dicts(keys_so_far, key_sequences, i, result):
    """Generate all combinations of items from key_sequences and,
       for each one, append the result of calling build_dict
       on it to result."""
    if i == len(key_sequences):
        result.append(build_dict(keys_so_far, 0))
    else:
        for key in key_sequences[i]:
            build_dicts(keys_so_far + (key,), key_sequences, i+1,
result)

def build_dict(keys, i):
    """Given a tuple of keys, generate nested sequence of
dictionaries."""
    if i == len(keys):
        return keys
    else:
        return {keys[i]: build_dict(keys, i+1)}

Hope that helps,
Greg




More information about the Python-list mailing list