Dan Crosta on 24 Dec 2005 23:56:55 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] python, list comprehensions


Jeff Abrahamson wrote:
I just wrote the following loop in python, which sums those values of
the matrix W that have the property that their distinct coordinates
are both in a set called H:

        for i in range(len(k)):
            for j in range(len(k)):
                if(i != j and i in H and j in H):
                    w += W[i,j]

I feel I ought to be able to do this with a list comprehension, but
it's not clear how to get the double loop.  Any thoughts?

        w = sum([W[i,j] for ?? ])


I don't think so -- or at least, I can't figure out a syntax to make it work. However, especially if your matrix is large, it probably makes more sense to iterate over the set H rather than over the matrix:


for i in H:
    for j in H:
        if i is not j:
            sum += W[i, j]

plus this saves the creation of the two range() arrays (actually -- someone might know if python optimizes this somehow, I've never looked at how it actually executes the code). I'm pretty certain python is optimized for iteration, so

for item in H:

is better than

for i in range(len(H)):
    item = H[i]

dsc
___________________________________________________________________________
Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug