Given a list of lists, the task is to find the count of unique sublists within list. Examples:
Input: [['Geek', 'for', 'geeks'], ['geeks', 'for'],
['for', 'Geeks', 'geek'], ['Geek', 'for', 'geeks']]
Output:
{('geeks', 'for'): 1, ('for', 'Geeks', 'geek'): 1,
('Geek', 'for', 'geeks'): 2}
Below are some ways to achieve the task. Method #1: Using Iteration
Python3
Input = [[ 'Geek' , 'for' , 'geeks' ], [ 'geeks' , 'for' ],
[ 'for' , 'Geeks' , 'geek' ], [ 'Geek' , 'for' , 'geeks' ]]
Output = {}
for lis in Input :
Output.setdefault( tuple (lis), list ()).append( 1 )
for a, b in Output.items():
Output[a] = sum (b)
print (Output)
|
Output:{(‘Geek’, ‘for’, ‘geeks’): 2, (‘geeks’, ‘for’): 1, (‘for’, ‘Geeks’, ‘geek’): 1}
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2: Using Counter
Python3
from collections import Counter
lst = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 3 , 2 , 1 ], [ 1 , 2 , 3 ]]
Output = Counter([ tuple (i) for i in lst])
print (Output)
|
Output:Counter({(1, 2, 3): 2, (3, 2, 1): 1, (4, 5, 6): 1})
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant space needed
Method #3: Using Pandas
Python3
from collections import Counter
import pandas as pd
lst = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 3 , 2 , 1 ], [ 1 , 2 , 3 ]]
dict = Counter([ tuple (i) for i in lst])
Output = pd.DataFrame(data = { 'list' : list ( dict .keys()),
'count' : list ( dict .values())})
print (Output)
|
Output:count list
0 1 (3, 2, 1)
1 1 (4, 5, 6)
2 2 (1, 2, 3)
Time Complexity: O(n), where n is the length of the list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list