将全零推到列表的一侧

时间:2014-06-08 13:26:00

标签: python

您好我试图将列表中的所有零推送到一侧而不改变其余部分:
[0,2,0,0,9] -> [0,0,0,2,9]
[3,4,0,1,0] -> [0,0,3,4,1]

我的解决方案:

def getNonZeros(self, tup):
    for i in tup:
        if i != 0:
            yield i;

def pushZeros(self, tup, side):
    if side==Side.End:
        return [i for i in self.getNonZeros(tup)] + [0]*tup.count(0);
    else:
        return [0]*tup.count(0) + [i for i in self.getNonZeros(tup)];

我在ipython中遇到了这个错误:

ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/IPython/core/ultratb.py", line 760, in     structured_traceback
    records = _fixed_getinnerframes(etb, context, tb_offset)
  File "/usr/lib/python2.7/site-packages/IPython/core/ultratb.py", line 242, in     _fixed_getinnerframes
    records  = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
  File "/usr/lib64/python2.7/inspect.py", line 1043, in getinnerframes
    framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
  File "/usr/lib64/python2.7/inspect.py", line 1007, in getframeinfo
    lines, lnum = findsource(frame)
  File "/usr/lib64/python2.7/inspect.py", line 580, in findsource
    if pat.match(lines[lnum]): break
IndexError: list index out of range

Unfortunately, your original traceback can not be constructed.

3 个答案:

答案 0 :(得分:10)

由于Python排序本质上是stable,所以你可以简单地做到这一点

>>> sorted([0,2,0,0,9], key=lambda x: x != 0)
[0, 0, 0, 2, 9]
>>> sorted([3,4,0,1,0], key=lambda x: x != 0)
[0, 0, 3, 4, 1]

答案 1 :(得分:2)

l=[3,4,0,1,0]

new_l = [x for x in l if x!=0]+[0 for y in range(l.count(0))]
[3, 4, 1, 0, 0]

时间安排:

In [23]: %timeit [x for x in l if x!=0]+[0 for y in range(l.count(0))]
1000000 loops, best of 3: 752 ns per loop

In [24]: %timeit sorted([3,4,0,1,0], key=lambda x: x != 0)
1000000 loops, best of 3: 1.41 µs per loop

或者:

In [25]: %timeit [x for x in l if x != 0] + [0]*  l.count(0)
1000000 loops, best of 3: 582 ns per loop

答案 2 :(得分:1)

只需使用自定义键对列表进行排序:

In [1]: L = [3, 4, 0, 1, 0]

In [2]: L.sort(key=lambda x: -1 if x == 0 else 1)

In [3]: L
Out[3]: [0, 0, 3, 4, 1]

注意:

  • 排序为guaranteed to be stable,因此保留所有数字相对顺序
  • 当输入几乎已经排序时,排序使用tim-sort,这是O(n),并且就是这种情况(请记住,只比较了键,这意味着只有非有序的点才是你的有一个0后跟一个不同的数字或相反的。)