this is simple...

Daniel da Silva ddasilva at umd.edu
Sat Jun 28 02:02:47 EDT 2008


ToshiBoy,

You might want to take a look at the filter() function, it can also be used
for the kind of the thing you're doing.

http://docs.python.org/tut/node7.html#SECTION007130000000000000000

>>> B = range(1,27)
>>> def test(b):
...     if b*b in B:
...             return True
...     else:
...             return False
...
>>> A = filter(test, B)
>>> A
[1, 2, 3, 4, 5]

Daniel

On Sat, Jun 28, 2008 at 1:00 AM, ToshiBoy <ToshiBoy at gmail.com> wrote:

> On Jun 28, 2:48 pm, Mel <mwil... at the-wire.com> wrote:
> > ToshiBoy wrote:
> > > I have two lists A and B that are both defined as range(1,27) I want
> > > to find the entries that are valid for A = BxB
> > [ ... ]
> > > I get, as expected 1,4,9,16,25 printed out being the only members of B
> > > where the condition is true, but when I print B I get:
> >
> > > [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]
> >
> > > 1 to 5 is correct, but why doesn't the remove method remove 7 and
> > > above? What am I doing wrong here?
> >
> > Try this:
> >
> > A = range(1,27)
> > B = range(1,27)
> > C = []
> >
> > for b in B:
> >     print "Trying", b
> >     if b*b in A:
> >         print b
> >         C.append (b)
> >     else:
> >         print "Removing", b
> >         B.remove(b)
> > print 'B', B
> > print 'C', C
> >
> > The essential problem is that your `B.remove`s are pulling the rug out
> from
> > under your `for b in B:`.  There are ways to mess with B while you
> iterate.
> > Running though B backwards will do: `for b in B[::-1]:`, or iterating
> over
> > a copy of B: `for b in B[:]:` or `for b in list(B):`.  Leaving B alone
> and
> > building up the desired items in C is probably simplest.
> >
> >         Mel.
>
> Thank you, of course! :-) Didn't even think of that... that I was
> modifying my iterators...
>
> Thank you
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080628/e6c9cc60/attachment-0001.html>


More information about the Python-list mailing list