delete duplicate columns in python list

I have the following list as example:

ls=[
    [1, 2, 3, 3, 4, 5, 5, 5, 6],
    ['a', 'a', 'b', 'b', 'c', 'd', 'e', 'f', 'g'],
    ['r', 's' ,'t', 'u', 'v', 'w', 'x', 'y', 'z']
]

And I want to delete duplicate elements such that once a duplicate is detected, its index must be used to delete all the element having this index in the other rows. The result of example must be:

[
[1, 3, 4, 5, 6],
['a', 'b', 'c', 'd', 'g'],
['r', 't', 'v', 'w', 'z']
]

I wrote the following code:

#Helping function to delete the elements of col_index from all rows
def delete_col(l, col_index):
    for sl in l:
        del sl[col_index]

#To delete the duplicates.
def list_without_columns_duplicates(l):
    i=0
    j=1
    while i<len(l):
        while j<len(l[0]):
            if l[i][j]==l[i][j-1]:
                delete_col(l, j)
            j+=1
        i+=1

However, I found two problems with when I run this code: (1) It considers the duplicates of the first row only, and (2) It delete only the first duplication and needs multiple runs to delete all the other duplicates. Any help will be appreciated.



Read more here: https://stackoverflow.com/questions/64941732/delete-duplicate-columns-in-python-list

Content Attribution

This content was originally published by Mus at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: