简体   繁体   English

如何从列表中删除所有零

[英]How to to remove all zeros from a list

I want to remove all zeros from the list after sorting in descending order.我想在按降序排序后从列表中删除所有零。

for x in range (1,count):
    exec("col"+str(x) + "=[]")


with open (xvg_input, 'r') as num:

    line_to_end = num.readlines()
    for line in line_to_end:
        if "#" not in line and "@" not in line:
            line=list(map(float,line.split()))
            for x in range (2,count):
                exec("col" +str (x)+ ".append(line["+ str(x-1) + "])")
                exec("col" +str(x) + ".sort(reverse = True)")
                exec("while (col"+str(x) + ".count(0.000)):")
                exec("col" +str(x) +".remove(0.000)")

I am getting the syntax error.我收到语法错误。 I am not getting where I am doing wrong.我没有得到我做错的地方。 I just want to sort in descending order and delete all the zeroes.我只想按降序排序并删除所有零。

Does this make sense这有意义吗

def remove_values(the_list, val):
   return [value for value in the_list if value != val]

x = [1, 0, 3, 4, 0, 0, 3]
x = remove_values(x, 0)
print x
# [1, 3, 4, 3]

Try using filter method:尝试使用过滤方法:

list = [9,8,7,6,5,4,3,2,1,0,0,0,0,0,0]
filter(lambda x: x != 0,a) #iterates items, returning the ones that meet the condition in the lambda function
# [9, 8, 7, 6, 5, 4, 3, 2, 1]

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

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