Move all zeroes to the beginning of a list in Python

后端 未结 4 1215
-上瘾入骨i
-上瘾入骨i 2020-11-29 13:00

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

4条回答
  •  醉梦人生
    2020-11-29 13:11

    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]
    

提交回复
热议问题