Jeff Abrahamson on 25 Dec 2005 02:18:43 -0000


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

Re: [PLUG] python, list comprehensions


On Sat, Dec 24, 2005 at 06:56:29PM -0500, Dan Crosta wrote:
>   [43 lines, 228 words, 1446 characters]  Top characters: teio_nar
> 
> 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]

Good idea.  I was thinking of it backwards.  H is *much* smaller than
len(k)^2 in my application.  Thanks.

-- 
 Jeff

 Jeff Abrahamson  <http://www.purple.com/jeff/>    +1 215/837-2287
 GPG fingerprint: 1A1A BA95 D082 A558 A276  63C6 16BF 8C4C 0D1D AE4B

Attachment: signature.asc
Description: Digital signature

___________________________________________________________________________
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