Python | Add occurrences of each number 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 for displaying the list 2d: [[& # 39; item1 & # 39 ;, & # 39; count1 & # 39;], [& # 39; item2 & # 39 ;, & # 39; count2 & # 39;], … , [& # 39; itemN & # 39 ;, & # 39; countN & # 39;]].

Code # 1: Using the count () method

# Python program to add an entry
# of each number as sublists

def count_occur (list1, * * kwargs):

  

  # iterate over the list item

for i in list1:

row = []

ct = 0

 

The # count function will count occurrences

ct = list1.count (i)

row.append (i)

row .append (ct)

# add 1d list items to 2d list

list2.append (row)

 

  # code below to eliminate

# duplicate list items

  for j in list2:

if j not in unq_l2:

unq_l2.append (j)

  

return unq_l2

 
Driver code

l1 = [ 3 , 5 , 7 , 2 , 3 , 5 , 9.1 ]

list2 = []

unq_l2 = []

print (count_occur (l1))

Exit:

 [[3, 2 ], [5, 2], [7, 1], [2, 1], [9.1, 1]] 

Code # 2: Using the loop method

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)):

  # match items from both lists

if l1 [i] = = l1 [j]:

  # when the match counter is increased by 1

  a = a + 1

row.append (l1 [i])

row.append (a)

# append function will add

  # 1d list of items in 2d list

  l.append (row)

 

  # below code to fix

# duplicate list items

for in l:

  if j not in unq_l:

unq_l.append (j )

 

return unq_l

  
# Driver code

l1 = [ 3 , 5 , 7 , 2 , 3 , 5 , 9.1 ]

l = []

unq_l = []

 

print (count_occur (l1 )) 

Exit:

 [ [3, 2], [5, 2], [7, 1], [2, 1], [9.1, 1]]