python列表元素零的移动,在Python中将所有零移动到列表的开头

I have a list like below:

a = [4, 5, 0, 0, 6, 7, 0, 1, 0, 5]

and I want to push all zeroes to the beginning of that list. The result must be like below.

a = [0, 0, 0, 0, 4, 5, 6, 7, 1, 5]

How to do it in Python 2?

解决方案

You could sort the list:

a.sort(key=lambda v: v != 0)

The key function tells Python to sort values by wether or not they are 0. False is sorted before True, and values are then sorted based on their original relative position.

For 0, False is returned, sorting all those values first. For the rest True is returned, leaving sort to put them last but leave their relative positions untouched.

Demo:

>>> a = [4, 5, 0, 0, 6, 7, 0, 1, 0, 5]

>>> a.sort(key=lambda v: v != 0)

>>> a

[0, 0, 0, 0, 4, 5, 6, 7, 1, 5]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值