pythonfunctionsortingnested-listscustom-lists

Function to sort list of lists into groups that share an item


My code is intended to sort a list of lists into the following examples.

I would like to group all [Y,x,x]'s with each other.

C = [[1,2,3],[4,5,7],[7,8,9],[1,2,4],[4,5,6]]

Intended Output

Notice that my Y is bolded

sorted C = [[1,2,3],[1,2,4],[4,5,7],[4,5,6],[7,8,9]]

c = [[4,5,10],[1,2,3],[4,5,6],[1,7,9],[1,2,8],[4,5,9],[1,7,8],[4,5,12],[9,8,7]]
sc = []

def sorting():
    
    for a in range(0, len(c)):
        for b in c[a+1:]:
            # prevent duplicates
            if b not in sc:
                if c[a] not in sc:
                    if c[a][0] == b[0]:
                        sc.append(b)
                        sc.append(c[a])
    for z in c:
        if z not in sc:
            for a in range(0, len(sc)):
                if sc[a][0] == z[0]:
                    if sc.count(z) < 1:
                        # insert missing list into intended location
                        sc.insert(a, z)
    # Append lists that may have been missed (eg. [9,8,7])                    
    for zz in c:
        if sc.count(zz) < 1:
            sc.append(zz)

sorting()
print(sc)

Error Output

This function has a semantic bug as it is outputting a [4,x,x] in the wrong location. As shown in the example all [Y,x,x]'s are supposed to be grouped together.

[[4, 5, 6], [4, 5, 10], [1, 7, 9], [1, 2, 3], [1, 7, 8], [1, 2, 8], [4, 5, 12], [4, 5, 9], [9, 8, 7]]

Question

What would a more professional function look like to sort my lists as intended?

What mistakes am I doing that causes an invalid output?


Solution

  • try to use lambda function to the sort function, in order to sort by the first element only. try this:

    c = [[4,5,10],[1,2,3],[4,5,6],[1,7,9],[1,2,8],[4,5,9],[1,7,8],[4,5,12],[9,8,7]]
    
    a = sorted(c, key=lambda parameter: parameter[0])   # sort by first element in item
    print(a)
    

    output:

    [[1, 2, 3], [1, 7, 9], [1, 2, 8], [1, 7, 8], [4, 5, 10], [4, 5, 6], [4, 5, 9], [4, 5, 12], [9, 8, 7]]