osdir.com


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

Test 0 and false since false is 0


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]