Python | Add the occurrence of each number as sublists
Last Updated :
07 Jan, 2023
Given a list of numbers, the task is to count the occurrence of each element and add as sublists.
Examples:
Input: l1 = [3, 5, 7, 2, 3, 5, 9.1]
Output: [[3, 2], [5, 2], [7, 1], [2, 1], [9.1, 1]]
Input: l1 = [1, 1, 2, 2, 3, 1]
Output: [[1, 3], [2, 2], [3, 1]]
Note: Format output 2d list is [[‘item1’, ‘count1’], [‘item2’, ‘count2’], …, [‘itemN’, ‘countN’]].
Code #1: Using count() method
python
def count_occur(list1, * * kwargs):
for i in list1:
row = []
ct = 0
ct = list1.count(i)
row.append(i)
row.append(ct)
list2.append(row)
for j in list2:
if j not in unq_l2:
unq_l2.append(j)
return unq_l2
l1 = [ 3 , 5 , 7 , 2 , 3 , 5 , 9.1 ]
list2 = []
unq_l2 = []
print (count_occur(l1))
|
Output:
[[3, 2], [5, 2], [7, 1], [2, 1], [9.1, 1]]
Code #2: Using loop method
python
def count_occur(list1):
for i in range ( 0 , len (l1)):
a = 0
row = []
if i not in l:
for j in range ( 0 , len (l1)):
if l1[i] = = l1[j]:
a = a + 1
row.append(l1[i])
row.append(a)
l.append(row)
for j in l:
if j not in unq_l:
unq_l.append(j)
return unq_l
l1 = [ 3 , 5 , 7 , 2 , 3 , 5 , 9.1 ]
l = []
unq_l = []
print (count_occur(l1))
|
Output:
[[3, 2], [5, 2], [7, 1], [2, 1], [9.1, 1]]
Code #3: Using counter() method
python
from collections import Counter
def count_occurence(l):
c = Counter(l)
l1 = []
for k,v in c.items():
l1.append([k,v])
return l1
l = [ 3 , 5 , 7 , 2 , 3 , 5 , 9.1 ]
print (count_occurence(l))
|
Output:
[[2, 1], [3, 2], [9.1, 1], [5, 2], [7, 1]]
Code #4: Using set and list comprehension
You can use a set to eliminate duplicates in the input list and a list comprehension to count the occurrence of each element.
Python3
def count_occur(l):
unique_elements = set (l)
return [[elem, l.count(elem)] for elem in unique_elements]
l1 = [ 3 , 5 , 7 , 2 , 3 , 5 , 9.1 ]
print (count_occur(l1))
|
Output
[[2, 1], [3, 2], [5, 2], [7, 1], [9.1, 1]]
The time complexity of this approach is O(n^2) because it uses two nested loops. The outer loop iterates over the elements of the list, and the inner loop counts the number of occurrences of each element. The space complexity is O(n) because it creates a new list with the same number of elements as the input list.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...