Moving all zeros to the end of the list while leaving False alone

前端 未结 1 993
天命终不由人
天命终不由人 2021-01-16 00:49

Suppose I have a list: [9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9,False] and I want to move all zeros to the end.

I know I can use:

s         


        
相关标签:
1条回答
  • 2021-01-16 01:29

    Since bool is a subclass of int and False == 0 is True (indeed, the success of our sorted key function depends on this), if you wish to treat False as non-zero, then you'll need to add that as another condition:

    sorted([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9,False], 
           key=lambda x: (x == 0) and x is not False)
    

    yields

    [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, False, 0.0, 0, 0, 0, 0.0, 0, 0, 0, 0, 0]
    
    0 讨论(0)
提交回复
热议问题