osdir.com


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

Test 0 and false since false is 0


> 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]

I have been reading this solution 
> >>> after = sorted(before, key=lambda x: x == 0 and type(x) == int)

it is really good, however I don't understand it enough to reimplement something like that myself yet.

Though I can that lambda tests for 0 that is equal to an int why does sorted put them to the end?

Cheers

Sayth