Home > Software engineering >  This is the inputlist input_list =[1,0,3,2,0,1,0] and I want output_list as [1,1,2,3,0,0,0] How to s
This is the inputlist input_list =[1,0,3,2,0,1,0] and I want output_list as [1,1,2,3,0,0,0] How to s

Time:01-23

input_list =[1,0,3,2,0,1,0]

for a in input_list:
    if input_list[a] != 0:
        input_list[a] = a 
    else:
        input_list[a] = 0
        
print(input_list)

Tried this but getting output as input_list =[1,0,3,2,0,1,0] Instead i want this [1,1,2,3,0,0,0]

for a in input_list:
    if input_list[a] != 0:
        input_list[a] = a 
    else:
        input_list[a] = 0
        
print(input_list)

CodePudding user response:

getting output as input_list

No, your code gives [0, 0, 3, 3, 0, 1, 0], because you use the values as indexes, for a in input_list iterates over values, then you use them input_list[a] as indexes


What you need is sorting, x or float('inf') expression takes inf in case the value of x is 0 (putting it at the end of the list), else it takes the value of x

input_list = [1, 0, 3, 2, 0, 1, 0]
result = sorted(input_list, key=lambda x: x or float('inf'))
print(result)

CodePudding user response:

You can make a custom sort where you give 0 infinite weight so it appears at the end of the sorting order.

output_list = sorted(input_list, key=lambda x: x if x != 0 else float('inf'))

CodePudding user response:

input_list =[1,0,3,2,0,1,0]
input_list.sort()
new_list = [el for el in input_list if el != 0]   [el for el in input_list if el == 0]

Output:

[1, 1, 2, 3, 0, 0, 0]

CodePudding user response:

I think the cleanest way to solve this is:

import math
input_list =[1,0,3,2,0,1,0]

input_list = sorted(input_list, key=lambda x: x if x!=0 else math.inf)

Which is sorting like one would usually do, but giving the 0 a weight of inf (infinite) such that it's always the last item.

  • Related