如何将python列表或numpy数组中的所有非零元素移到一侧? [英] how to move all non-zero elements in a python list or numpy array to one side?

查看:270
本文介绍了如何将python列表或numpy数组中的所有非零元素移到一侧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将对列表或numpy数组执行以下操作:

I'm going to do the following operation of a list or numpy array:

[0, 0, 0, 1, 0, 0, 4, 2, 0, 7, 0, 0, 0]

将所有非零移动到右侧:

move all non-zeros to the right side:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 2, 7]

如何有效地做到这一点?

How can I do this efficiently?

谢谢

============

============

抱歉,我不清楚,我需要保留非零元素的顺序.

Sorry I didn't make it clear, I need the order of non-zeros elements remains.

推荐答案

使用NumPy:

>>> a = np.array([0, 0, 0, 1, 0, 0, 4, 2, 0, 7, 0, 0, 0])
>>> np.concatenate((a[a==0], a[a!=0]))
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 2, 7])

您也可以使用简单的for循环在Python中的O(N)时间执行此操作.但是会占用一些额外的内存,我们可以通过使用a.sort(key=bool)

You can do this in O(N) time in Python as well by using a simple for-loop. But will take some extra memory which we can prevent in @grc's solution by using a.sort(key=bool):

>>> from collections import deque
#Using a deque
>>> def solve_deque(lst):
    d = deque()
    append_l = d.appendleft
    append_r = d.append
    for x in lst:
        if x:
            append_r(x)
        else:
            append_l(x)
    return list(d) #Convert to list if you want O(1) indexing.
...
#Using simple list
>>> def solve_list(lst):                           
    left = []                                    
    right = []
    left_a = left.append
    right_a = right.append
    for x in lst:
        if x:
            right_a(x)
        else:
            left_a(x)
    left.extend(right)
    return left

>>> solve_list([0, 0, 0, 1, 0, 0, 4, 2, 0, 7, 0, 0, 0])
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 2, 7]
>>> solve_deque([0, 0, 0, 1, 0, 0, 4, 2, 0, 7, 0, 0, 0])
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 2, 7]

这篇关于如何将python列表或numpy数组中的所有非零元素移到一侧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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