Search code examples
pythonlistlong-integershort

how to delete the short lists from a long nested list even the items are not continuous using Python?


For example:

t=[[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [3, 5], [4, 5, 6],[4,5,6],[6,7], [6], [1]]

I want to delete the short lists if the items are included in a long one, even the items are not continuous. So, I expect the result to be:

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

I might figure out this by myself, but my way is not smart enough. Could anyone help me here?


Solution

  • Since all the elements in a list is unique, AND I like using sets here's my code. Haven't checked it's efficiency but it looks cleaner :D

    t = [[1, 2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [2, 3, 4, 5, 6], [3, 5], [4, 5, 6],[4,5,6],[6,7], [6], [1]]
    
    t = [set(l) for l in t]
    t = [list(x) for x in t if not any([x.issubset(y) for y in t if x != y])]