Skip to main content
 首页 » 编程设计

python之从列表末尾删除零

2025年05月04日8dflying

函数在参数列表中接收末尾有很多 0 的参数,例如:

[48, 39, 23, 15, 11, 12, 5, 9, 7, 3, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0] 
[137, 30, 12, 3, 1, 0, 0, 0] 

如果列表的长度和末尾零的数量总是不同,我如何从零开始修剪它以得到

[48, 39, 23, 15, 11, 12, 5, 9, 7, 3, 4, 2, 0, 0, 1, 0 , 1] 
[137, 30, 12, 3, 1] 

请您参考如下方法:

list1 = [48, 39, 23, 15, 11, 12, 5, 9, 7, 3, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0] 
list2 = [137, 30, 12, 3, 1, 0, 0, 0] 
 
 
def pop_zeros(items): 
    while items[-1] == 0: 
        items.pop() 
 
pop_zeros(list1) 
pop_zeros(list2) 
print(list1) 
print(list2) 

输出

[48, 39, 23, 15, 11, 12, 5, 9, 7, 3, 0, 0, 1, 0, 1] 
[137, 30, 12, 3, 1]