将所有零移动到列表的末尾,同时不保留False [英] Moving all zeros to the end of the list while leaving False alone
问题描述
假设我有一个列表:[9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9,False]
,我想将所有零移动到末尾.
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.
我知道我可以使用:
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)
,但它也会将False
移到列表的末尾,这不是我想要的.
but it will move False
to the end of the list as well, which is not what I want.
如何仅移动零,而将False
值保留在其原始位置?
How do I move only zeroes but leave False
values at their original places?
推荐答案
由于bool
是int
的子类,而False == 0
是True(实际上,sorted
key
函数的成功取决于这样),如果您希望将False
视为非零,则需要将其添加为另一个条件:
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)
收益
[9, 9, 1, 2, 1, 1, 3, 1, 9, 9, False, 0.0, 0, 0, 0, 0.0, 0, 0, 0, 0, 0]
这篇关于将所有零移动到列表的末尾,同时不保留False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!