Home > Blockchain >  Removing non-unique items from list of lists
Removing non-unique items from list of lists

Time:08-06

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']]

CodePudding user response:

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

CodePudding user response:

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!

CodePudding user response:

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']]
  • Related