将所有零移动到列表的末尾,同时不保留False [英] Moving all zeros to the end of the list while leaving False alone

查看:72
本文介绍了将所有零移动到列表的末尾,同时不保留False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个列表:[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?

推荐答案

由于boolint的子类,而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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆