Search code examples
pythonmatlabunique

Python equivalent of Unique function in Matlab


I have a (654 x 2) matrix of integers where many rows are having values which are just permutations of the same column values. (Eg. a certain row has values [2,5] whereas another row has values [5,2]). I need a Python function which treats both the rows as unique and help me deleting the row which comes later when sorted.


Solution

  • Sort each element in the sublist.

    a = [[1,2], [3, 4], [2,1]]
    
    #Sorted each element in sublist, I converted list to tuple to provide it as an input in set
    li = [tuple(sorted(x)) for x in a]
    print(li)
    #[(1, 2), (3, 4), (1, 2)]
    

    Then use set to eliminate duplicates.

    #Convert tuple back to list
    unique_li = [list(t) for t in set(li)]
    print(unique_li)
    #[[1, 2], [3, 4]]