Search code examples
pythonlistfor-loopdifference

How can I difference each element among list of list?


I am trying to write a python code and I have a list of list like as below: [[1],[1,2],[3,4],[3],[4,5,6],[2,5,7,8]] I want to use each element for difference above element, for example: the first element will difference with itself and the second will difference the first element the third element will difference the first element and second element etc.

first= list(set([1]).difference(set([1)))
second= list(set([1,2]).difference(set([1)))
third= list(set([3,4]).difference(set([1,2])).difference(set([1])))
Fourth= list(set([3]).difference(set([3,4])).difference(set([1,2])).difference(set([1])))

and the "return" will [first,second,third,Fourth........]

Does any one have any idea? thx


Solution

  • I have slightly changed the implementation suggested by @OmarAflak in the comments. Reusing the intermediate results will not work in case the intermediate result is an empty list [], to overcome this I have a set prev that keeps track of all the elements seen so far.

    def difference(seq):
        res = []
        prev = set(seq[0])
        for i in seq:
            res.append(list(set(i).difference(prev)))
            prev.update(i)
        return res
    
    seq =  [[1],[1,2],[3,4],[3],[4,5,6],[2,5,7,8]]
    res = difference(seq)
    print(res)
    
    seq =  [[1],[1,2],[3,4],[3],[4,5,6],[2,5,7,8], [1, 2, 18], [9]]
    res = difference(seq)
    print(res)
    

    Output

    [[], [2], [3, 4], [], [5, 6], [8, 7]]
    [[], [2], [3, 4], [], [5, 6], [8, 7], [18], [9]]