You'd be better off using the builtin "isinstance" function, e.g.:
isinstance(x, int). This also has the added benefit of working nicely with
inheritance (isinstance returns true if the actual type is derived from the
classinfo passed as the second argument). See
https://docs.python.org/3/library/functions.html#isinstance for details.

Regards,
Nathan

On Fri, Jul 7, 2017 at 2:04 AM, Peter Otten <__pete...@web.de> wrote:

> Sayth Renshaw wrote:
>
> > I was trying to solve a problem and cannot determine how to filter 0's
> but
> > not false.
> >
> > Given a list like this
> > ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]
> >
> > I want to be able to return this list
> > ["a","b",None,"c","d",1,False,1,3,[],1,9,{},9,0,0,0,0,0,0,0,0,0,0]
> >
> > However if I filter like this
> >
> > def move_zeros(array):
> >     l1 = [v for v in array if v != 0]
> >     l2 = [v for v in array if v == 0]
> >     return l1 + l2
> >
> > I get this
> > ['a', 'b', None, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, False, 0,
> 0,
> > [0, 0, 0, 0, 0]
> >
> > I have tried or conditions of v == False etc but then the 0's being false
> > also aren't moved. How can you check this at once?
> >
> >
> > Cheers
> >
> > Sayth
>
> Another option is to test for type(value) == int:
>
> >>> before = ["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,
> {},0,0,9]
> >>> wanted = ["a","b",None,"c","d",1,False,1,3,[],1,9,
> {},9,0,0,0,0,0,0,0,0,0,0]
> >>> after = sorted(before, key=lambda x: x == 0 and type(x) == int)
> >>> assert str(after) == str(wanted)
> >>> after
> ['a', 'b', None, 'c', 'd', 1, False, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0,
> 0, 0, 0, 0, 0]
>
>
> That way float values will be left alone, too:
>
> >>> sorted([0.0, 0, False, [], "x"], key=lambda x: x == 0 and type(x) ==
> int)
> [0.0, False, [], 'x', 0]
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to