Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique features between multiple lists

I am trying to find the unique differences between 5 different lists.

I have seen multiple examples of how to find differences between two lists but have not been able to apply this to multiple lists.

It has been easy to find the similarities between 5 lists.

Example:

list(set(hr1) & set(hr2) & set(hr4) & set(hr8) & set(hr24))

However, I want to figure out how to determine the unique features for each set.

Does anyone know how to do this?

like image 370
dhop Avatar asked Jun 11 '13 02:06

dhop


3 Answers

How's this? Say we have input lists [1, 2, 3, 4], [3, 4, 5, 6], and [3, 4, 7, 8]. We would want to pull out [1, 2] from the first list, [5, 6] from the second list, and [7, 8] from the third list.

from itertools import chain

A_1 = [1, 2, 3, 4]
A_2 = [3, 4, 5, 6]
A_3 = [3, 4, 7, 8]

# Collect the input lists for use with chain below
all_lists = [A_1, A_2, A_3]

for A in (A_1, A_2, A_3):
  # Combine all the lists into one
  super_list = list(chain(*all_lists))
  # Remove the items from the list under consideration
  for x in A:
    super_list.remove(x)
  # Get the unique items remaining in the combined list
  super_set = set(super_list)
  # Compute the unique items in this list and print them
  uniques = set(A) - super_set
  print(sorted(uniques))
like image 89
bbayles Avatar answered Sep 28 '22 02:09

bbayles


Could this help? I m assuming a list of lists to illustrate this example. But you can modify the datastructure to cater to your needs

from collections import Counter
from itertools import chain

list_of_lists = [
    [0,1,2,3,4,5],
    [4,5,6,7,8,8],
    [8,9,2,1,3]
]
counts = Counter(chain.from_iterable(map(set, list_of_lists)))
uniques_list = [[x for x in lst if counts[x]==1] for lst in list_of_lists]
#uniques_list = [[0], [6, 7], [9]]

Edit (Based on some useful comments):

counts = Counter(chain.from_iterable(list_of_lists))
unique_list = [k for k, c in counts.items() if c == 1]
like image 33
karthikr Avatar answered Sep 28 '22 02:09

karthikr


Using set differencing in a comprehension

def f(lol):
  return [[*set(lol[i]).difference(*lol[:i], *lol[i+1:])] for i in range(len(lol))]

Example #1

list_of_lists = [
    [0,1,2,3,4,5],
    [4,5,6,7,8,8],
    [8,9,2,1,3]
]

f(list_of_lists)

[[0], [6, 7], [9]]

Example #2

A_1 = [1, 2, 3, 4]
A_2 = [3, 4, 5, 6]
A_3 = [3, 4, 7, 8]

all_lists = [A_1, A_2, A_3]

f(all_lists)

[[1, 2], [5, 6], [7, 8]]
like image 40
piRSquared Avatar answered Sep 28 '22 02:09

piRSquared