-6

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.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
Ron Ledger
  • 35
  • 7
  • Please include the full traceback of the error. – glibdud Jul 31 '19 at 17:14
  • In general, you should use a list or dict instead of creating a dynamic number of variables. In this case, you could easily do it with either. `exec` is slow, unsafe, and makes debugging hard. – iz_ Jul 31 '19 at 17:15
  • Why are you doing this in such a convoluted way? You don't need all these `exec` calls. You can read the file into a list of lists with much fewer lines – DeepSpace Jul 31 '19 at 17:16
  • I know the fact, now I can't change, if there is any solution for this that will be heplful :( :( – Ron Ledger Jul 31 '19 at 17:22
  • Does this answer your question? [Is there a simple way to delete a list element by value?](https://stackoverflow.com/questions/2793324/is-there-a-simple-way-to-delete-a-list-element-by-value) – sa_leinad Jun 10 '22 at 03:57

2 Answers2

1

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]
midhun k
  • 546
  • 1
  • 12
  • 28
1

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]
  • In this case you don't need the lambda. If `None` is passed as the first argument then `filter` will return only the "true-ish" values. Since `bool(0)` is `False`, all zeros will be removed. `filter(None, a)` – DeepSpace Jul 31 '19 at 17:54
  • I am not geeting it. :( – Ron Ledger Jul 31 '19 at 18:05