简体   繁体   English

如何将python列表或numpy数组中的所有非零元素移到一侧?

[英]how to move all non-zero elements in a python list or numpy array to one side?

I'm going to do the following operation of a list or numpy array: 我将对列表或numpy数组执行以下操作:

[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? 我如何有效地做到这一点?

Thanks 谢谢

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

Sorry I didn't make it clear, I need the order of non-zeros elements remains. 抱歉,我不清楚,我需要保留非零元素的顺序。

You could sort the list by their boolean value. 您可以按其布尔值对列表进行排序。 All falsy values (just zero for numbers) will get pushed to the front of the list. 所有伪造的值(数字仅为零)将被推到列表的最前面。 Python's builtin sort appears stable, so other values will keep their relative position. Python的内置排序看起来很稳定,因此其他值将保持其相对位置。

Example: 例:

>>> a = [0, 0, 0, 1, 0, 0, 5, 2, 0, 7, 0, 0, 0]
>>> sorted(a, key=bool)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 5, 2, 7]

Using NumPy: 使用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])

You can do this in O(N) time in Python as well by using a simple for-loop. 您也可以通过使用简单的for循环在Python的O(N)时间执行此操作。 But will take some extra memory which we can prevent in @grc's solution by using a.sort(key=bool) : 但是会占用一些额外的内存,我们可以使用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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM