Search code examples
pythonpython-3.xlistmove

move specific values (based on that value) in each list of lists in python


I have a list of lists that looks like this:

list= [[0,1,0,0,0][0,0,0,2,0],...,[0,0,10,0,0]]

What i would like as the output, is to have all the values (1,2..,10) to move to the beginning of the list they are in, so something like :

list= [[1,0,0,0,0][2,0,0,0,0],...,[10,0,0,0,0]]

I have tried :

new_list= list.insert(0, list.pop(list.index(value)))

which works for one list, but I want to do it for all the lists inside the list.


Solution

  • You can sort:

    l = [[0,1,0,0,0],[0,0,0,2,0],[0,0,10,0,0]]
    print([sorted(i, reverse=True) for i in l])
    

    Output:

    [[1, 0, 0, 0, 0], [2, 0, 0, 0, 0], [10, 0, 0, 0, 0]]