[Solved] Python sorting a list of pairs


Here is a method to do what you are trying to achieve.

unsorted = [[1, 0], [2, 0], [3, 0], [4, 2], [5, 2], [6, 5], [7, 6], [8,0]]
sortList = []
sortDict = {}

for x in unsorted:
    if x[1] != 0:
        if x[1] in sortDict:
            sortDict[x[1]].append(x[0])
        else:
            sortDict[x[1]] = [x[0]]

for x in unsorted:
    if x[1] == 0:
        sortList.append(x)
    if x[0] in sortDict:
        sortList.extend([[y, x[0]] for y in sortDict[x[0]]])

print(sortList)

Result:

[[1, 0], [2, 0], [4, 2], [5, 2], [3, 0], [6, 5], [7, 6], [8, 0]]

I’ll keep trying to get it smaller (and better), but this may be the only way to do what you are asking.
I assume that the starting list is sorted by x[0] as in your example.

solved Python sorting a list of pairs