Change language

Python | Remove list items that are repeated less than k times

| |

Examples :

  Input:  lst = [’a’,’ a’, ’a’,’ b’, ’b’ , ’c’], k = 2  Output:  [’ a’, ’a’,’ a’, ’b’,’ b’]  Input:  lst = [1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4], k = 3  Output:  [1, 1, 1, 1, 3, 3, 3 ] 

Approach # 1: Python naive

Counter () from collections module creates a dictionary which maps values ​​to counters and stores them in & # 39; countted & # 39 ;. We then use temp_lst to store the items to be deleted. Finally, we go through the given list and add any items that are not in & # 39; temp_lst & # 39; to & # 39; res_lst & # 39; containing the required output.

# Python3 element remover
# a list that is repeated less than k times

from collections import Counter

 

def removeElements (lst, k):

  counted = Counter (lst)

 

temp_lst = []

for el in counted:

if counted [el] & lt; k:

temp_lst.append (el)

 

res_lst = []

for el in lst:

if el not in temp_lst:

res_lst.append (el)

 

return (res_lst)

 
# Driver code

lst = [ ’a’ , ’ a’ , ’a’ , ’ b ’ , ’ b’ , ’c’ ]

k = 2

print (removeElements (lst, k))

Exit:

 [’a’,’ a’, ’a’,’ b’, ’b’] 

Approach # 2: An Effective Approach

An efficient approach to using the Counter method is to create a dictionary mapping value for the counts and then use a list comprehension to filter out counts that exceed the specified value. This approach is efficient in terms of time and space.

# Python3 program to remove elements
# a list that repeats less than k times

from collections import Counter

 

def removeElements (lst, k):

  counted = Counter (lst)

return [el for el in lst if counted [el]" = k]

 
# Driver code

lst = [ ’ a’ , ’a’ , ’a’ , ’ b’ , ’ b’ , ’c’ ]

k = 2

print (removeElements (lst, k))

Exit:

 [’a’,’ a’ , ’a’,’ b’, ’b’] 

Python | Remove list items that are repeated less than k times Counters: Questions

Python | Remove list items that are repeated less than k times Python functions: Questions

Shop

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

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method