Change language

Python | Group list items by frequency

|

Examples :

  Input:  [1, 3, 4, 4, 1, 5, 3, 1]  Output:  [(1, 3), (3, 2), (4, 2), (5, 1)]  Input:  [’x’,’ a’, ’x’ , ’y’,’ a’, ’x’]  Output:  [(’ x’, 3), (’a’, 2), (’ y’, 1)] 

Method # 1: Understanding a List

We can use lists to form tuples of each element and a counter of its occurrence and store it in & # 39; res & # 39; but it will contain a duplicate of the first element. So, to remove the duplicate first item, we use OrderedDict (res) .items () .

# Python3 program to the list groupings
# frequency-based elements

from collections import OrderedDict 

  

def group_list (lst):

 

res =   [(el, lst.count (el)) for el in lst]

  return list (OrderedDict (res) .items ( ))

 
# Driver code

lst = [ 1 , 3 , 4 , 4 , 1 , 5 , 3 , 1 ]

print (group_list (lst))

Exit:

 [(1, 3), (3, 2), (4, 2), ( 5, 1)] 

Spo int # 2: Using collections.Counter()

collections.Counter () provides two direct methods keys () and values ​​() which provide elements and their occurrences. Finally, zip them together using the Python zip () method.

# Python3 program into grouping list
# frequency-based elements

from collections import Counter

 

def group_list (lst):

  

return list ( zip (Counter (lst) .keys (), Counter (lst). values ​​()))

 
# Driver code

lst = [ 1 , 3 , 4 , 4 , 1 , 5 , 3 , 1 ]

print (group_list (lst))

Exit:

 [(1, 3), (3, 2), (4, 2), (5 , 1)] 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically