问题
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