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

两盒软妹~` 提交于 2020-01-21 09:51:07

问题


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:

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

but it will move False to the end of the list as well, which is not what I want.

How do I move only zeroes but leave False values at their original places?


回答1:


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]


来源:https://stackoverflow.com/questions/42187105/moving-all-zeros-to-the-end-of-the-list-while-leaving-false-alone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!