Move all zeroes to the beginning of a list in Python

后端 未结 4 1218
-上瘾入骨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:19

    Try this simple process:-

    from collections import deque
    a = [4, 5, 0, 0, 6, 7, 0, 1, 0, 5]
    b = deque([x for x in a if x!=0])
    for i in a:
        if i==0:
            b.appendleft(0)
    print list(b)
    #output -> [0, 0, 0, 0, 4, 5, 6, 7, 1, 5]
    

提交回复
热议问题