doddy
doddy

Reputation: 609

Finding list containing unique elements in list of lists in python?

Say I have a list of lists like so:

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

I want to get the indices of the inner lists that contain unique elements. For the example above, the lists at index 2 is the only one that contains 7 and the list at index 3 is the only one that contains 6.

How would one go about implementing this in python?

Upvotes: 0

Views: 147

Answers (3)

Transhuman
Transhuman

Reputation: 3547

using itertools.chain with set.difference(set)

from itertools import chain
l = [[1,2,3,4],[4,5,3,2],[7,8,9,2],[5,6,8,9]]
[i for i in range(len(l)) if set(l[i]).difference(set(chain(*[j for j in l if j!=l[i]])))]
#[0, 2, 3]

Upvotes: 0

cs95
cs95

Reputation: 402293

Here's a solution using Counter. Each inner list is checked for a value that only has a single count, and then the corresponding index is printed (a la enumerate).

from collections import Counter
from itertools import chain

c = Counter(chain.from_iterable(l))
idx = [i for i, x in enumerate(l) if any(c[y] == 1 for y in x)] 

print(idx)
[0, 2, 3]

A possible optimisation might include precomputing unique elements in a set to replace the any call with a set.intersection.

c = Counter(chain.from_iterable(l))
u = {k for k in c if c[k] == 1}

idx = [i for i, x in enumerate(l) if u.intersection(x)]

Upvotes: 4

mshsayem
mshsayem

Reputation: 18008

A naive solution:

>>> from collections import Counter
>>> from itertools import chain
>>> my_list = [[1,2,3,4],[4,5,3,2],[7,8,9,2],[5,6,8,9]]
# find out the counts.
>>> counter = Counter(chain(*my_list))
# find the unique numbers
>>> uniques = [element for element,count in counter.items() if count==1]
# find the index of those unique numbers
>>> result = [indx for indx,elements in enumerate(my_list) for e in uniques if e in elements]
>>> result
[0, 2, 3]

Upvotes: 1

Related Questions