繁体   English   中英

删除Python列表中的所有尾随零

[英]Remove all trailing zeroes in Python list

有没有比这更快的删除零的方法:

while L[-1] == 0:
    L.pop(-1)

任何预建功能或类似的东西?

三种可能的微观优化:

1.使用del my_list[index] ,而不是mylist.pop(index) ,当你想通过它的索引只是删除的项目。

它稍快一点:

import dis
def del_by_pop(mylist):
    mylist.pop(-1)

def del_by_del(mylist):
    del mylist[-1]

使用dis模块,我们可以看看下面发生了什么。

dis.dis(del_by_pop)打印以下内容:

  2           0 LOAD_FAST                0 (mylist)
              3 LOAD_ATTR                0 (pop)
              6 LOAD_CONST               2 (-1)
              9 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             12 POP_TOP
             13 LOAD_CONST               0 (None)
             16 RETURN_VALUE

dis.dis(del_by_del)打印以下内容:

  2           0 LOAD_FAST                0 (mylist)
              3 LOAD_CONST               2 (-1)
              6 DELETE_SUBSCR
              7 LOAD_CONST               0 (None)
             10 RETURN_VALUE

del工作量较少,因为它不需要返回弹出的项目。

2.使用for循环而不是while循环。

def del_for(mylist):
    for i in reversed(mylist):
        if not i:
            del mylist[-1]
        else:
            break

3.根本不使用del ,只需在找到最后一个非零项目的位置后对列表进行切片

def del_for(mylist):
    for i, j in enumerate(reversed(mylist)):
        if j:
            mylist = mylist[:-1*i]
            break

使用del并删除一次:

# rstrip_list.py

def rstrip(L, hit):
    while L[-1] == hit:
        L.pop(-1)

def fast_rstrip(L, hit):
    for i in xrange(len(L) - 1, -1, -1):
        if L[i] != hit:
            break
    del L[i + 1:]

import cProfile

L1 = range(1, 1000000) + [0] * 10000
L2 = range(1, 1000000) + [0] * 10000

cProfile.run('rstrip(L1, 0)')
cProfile.run('fast_rstrip(L2, 0)')

结果:

$ python rstrip_list.py

         10003 function calls in 0.004 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.004    0.004 <string>:1(<module>)
    1    0.003    0.003    0.004    0.004 rstrip_list.py:5(rstrip)
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
    10000    0.001    0.000    0.001    0.000 {method 'pop' of 'list' objects}


         4 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.001    0.001 <string>:1(<module>)
        1    0.001    0.001    0.001    0.001 rstrip_list.py:10(fast_rstrip)
        1    0.000    0.000    0.000    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

我认为L是一个列表或一个字符串。 您可以使用:

L = ''.join(L).rstrip('0')

暂无
暂无

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

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