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.
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]]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With