Anyone happen to have optimization hints for this loop?

Paul Hankin paul.hankin at gmail.com
Wed Jul 9 15:49:41 EDT 2008


On Jul 9, 5:04 pm, dp_pearce <dp_pea... at hotmail.com> wrote:
> count = 0
> dmntString = ""
> for z in range(0, Z):
>     for y in range(0, Y):
>         for x in range(0, X):
>             fraction = domainVa[count]
>             dmntString += "  "
>             dmntString += fraction
>             count = count + 1
>         dmntString += "\n"
>     dmntString += "\n"
> dmntString += "\n***\n
>
> dmntFile     = open(dmntFilename, 'wt')
> dmntFile.write(dmntString)
> dmntFile.close()
> Can anyone see a way of speeding this loop up?

I'd consider writing it like this:

def dmntGenerator():
    count = 0
    for z in xrange(Z):
        for y in xrange(Y):
            for x in xrange(X):
                yield '  '
                yield domainVa[count]
                count += 1
            yield '\n'
        yield '\n'
    yield '\n***\n'

You can make the string using ''.join:

dmntString = ''.join(dmntGenerator())

But if you don't need the string, just write straight to the file:

for part in dmntGenerator():
    dmntFile.write(part)

This is likely to be a lot faster as no large string is produced.

--
Paul Hankin




More information about the Python-list mailing list