How to create a sorted unique list from a matrix in Python

1 Answer

0 votes
"""
    Create a sorted unique list (lst) from a matrix (lst of lst).
    Steps:
      1. Flatten matrix into lst
      2. Sort lst (sorted)
      3. Remove duplicates (dict.fromkeys)
"""

def make_sorted_unique_lst(mat):
    # Flatten matrix into lst
    lst = [x for slc in mat for x in slc]   # slc = slice (row)

    # Sort lst
    lst = sorted(lst)

    # Remove duplicates while preserving order
    lst = list(dict.fromkeys(lst))

    return lst


mat = [
    [5, 1, 17, 3, 8, 2, 1, 9],
    [3, 5, 7, 4, 2, 3, 4, 1],
    [9, 1, 8, 2, 3, 88, 17, 5]
]

lst = make_sorted_unique_lst(mat)

for x in lst:
    print(x, end=" ")


"""
run:

1 2 3 4 5 7 8 9 17 88

"""

 



answered May 7 by avibootz
...