Home > Blockchain >  sorting multidimensional lists in python
sorting multidimensional lists in python

Time:05-02

a = ["1", "11.1", "1.11.1", ".1", "2", "2.2", "2.1.9", "2.2.1", "1.2", "1.01.1"]
b = []

for x in a:
    y = x.split(".")
    b.append(y)
    
j = sorted(b)

for jj in j:
    print (jj)

Results in:

['', '1']
['1']
['1', '01', '1']
['1', '11', '1']
['1', '2']
['11', '1']
['2']
['2', '1', '9']
['2', '2']
['2', '2', '1']

The desired output should be:

['', '1']
['1']
['1', '01', '1']
['1', '11', '1']
['1', '2']
['2']
['2', '1', '9']
['2', '2']
['2', '2', '1']
['11', '1']

The problem with the first output is 11 is not greater than 2, so the list is out of order. The correct or desired order is the second output.

I cant tell if the solution would require putting a 0 before the the other numbers somehow.

CodePudding user response:

The reason appears to be as the data is in string format. To sort it the way you are looking for, convert each element to int and then sort. You can get this by updating the code like this...

def to_int(val):
    try:
        return int(val)
    except ValueError:
        return 0
    
a = ["1", "11.1", "1.11.1", ".1", "2", "2.2", "2.1.9", "2.2.1", "1.2", "1.01.1"]
b = []

for x in a:
    y = x.split(".")
    y = [to_int(x) for x in y]
    b.append(y)
    
j = sorted(b)

for jj in j:
    print (jj)
  • Related