Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing `list`s in python

I have multiple lists. I need to find a way to generate list of unique items in each list as compared with all the lists. Is there any simple or straight forward way to do this. I know that these lists can basically be used as sets.

like image 968
Sam Avatar asked Sep 05 '26 16:09

Sam


2 Answers

import collections

def uniques(*args):
    """For an arbitrary number of sequences,
           return the items in each sequence which
            do not occur in any of the other sequences
    """

    # ensure that each value only occurs once in each sequence
    args = [set(a) for a in args]

    seen = collections.defaultdict(int)
    for a in args:
        for i in a:
            seen[i] += 1
    # seen[i] = number of sequences in which value i occurs

    # for each sequence, return items
    #  which only occur in one sequence (ie this one)
    return [[i for i in a if seen[i]==1] for a in args]

so

uniques([1,1,2,3,5], [2,3,4,5], [3,3,3,9])  ->  [[1], [4], [9]]
like image 61
Hugh Bothwell Avatar answered Sep 07 '26 04:09

Hugh Bothwell


Use the set class and the set operations defined therein:

>>> l1 = [1,2,3,4,5,5]
>>> l2 = [3,4,4,6,7]
>>> set(l1) ^ set(l2)    # symmetric difference
set([1, 2, 5, 6, 7])

edit: Ah, misread your question. If you meant, "unique elements in l1 that is not in any of l2, l3, ..., ln, then:

l1set = set(l1)
for L in list_of_lists:   # list_of_lists = [l2, l3, ..., ln]
    l1set = l1set - set(L)
like image 43
Santa Avatar answered Sep 07 '26 05:09

Santa