Removing non-unique items from list of lists

Question:

Given the following list

[['cat','dog','rabbit'],['cat','eagle','snail'],['crab','dog','fish'],['rat','bat','frog']]

How can I exclude any animal that appears more than once? I’m currently using a loop but am sure there is a better way.

The end result should look like this:

[['rabbit'],['eagle','snail'],['crab','fish'],['rat','bat','frog']]
Asked By: newbzzs

||

Answers:

you can use Counter or a dict from collections package in python to store count of each string in lists, then iterate over it and keep it if the count is 1

Answered By: sky

I did it with a for loop. Maybe too complex:

from copy import deepcopy

arr_of_arrays = [['cat','dog','rabbit'],['cat','eagle','snail'],['crab','dog','fish'],['rat','bat','frog']]

result = []
for arr in arr_of_arrays:
    temp_arr_of_arrays = deepcopy(arr_of_arrays)
    temp_arr_of_arrays.remove(arr)
    temp_arr = []
    for animal in arr:
        if not any(animal in arr_ for arr_ in temp_arr_of_arrays):
            temp_arr.append(animal)
    result.append(temp_arr)

print(result)

Output

[['rabbit'], ['eagle', 'snail'], ['crab', 'fish'], ['rat', 'bat', 'frog']]

Feedback appreciated!

Answered By: puncher

Here are the details for the answer from @sky:

from collections import Counter
from itertools import chain

lol = [
   ['cat', 'dog', 'rabbit'],
   ['cat', 'eagle', 'snail'],
   ['crab', 'dog', 'fish'],
   ['rat', 'bat', 'frog'],
]
cnt = Counter(chain.from_iterable(lol))
result = [[x for x in sublist if cnt[x] == 1] for sublist in lol]

This gives:

[['rabbit'],
 ['eagle', 'snail'],
 ['crab', 'fish'],
 ['rat', 'bat', 'frog']]
Answered By: Raymond Hettinger
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.