Deleting elements of a list based on a condition

  • A+

I have a list of elements from which I want to remove those elements whose count is less than or equal to 2 in all the list.

For example:

A = [['a','b','c'],['b','d'],['c','d','e'],['c','e','f'],['b','c','e','g']] 

I want to remove 'a', 'd', 'f', 'g' from A and store the rest in B so that the list becomes:

B = [['b','c'],['b'],['c','e'],['c','e'],['b','c','e']] 

I created a dictionary which will store all the count of elements and based on that I want to remove the elements with count less than or equal to 2.

Below is the code which I have written so far.

for i in range(len(A)):     for words in A[i]:         word_count[words] +=1     B = [A[i] for i in range(len(A)) if word_count[words]<2] 

You can use collections.Counter:

from collections import Counter import itertools A = [['a','b','c'],['b','d'],['c','d','e'],['c','e','f'],['b','c','e','g']] c = Counter(itertools.chain(*A)) new_a = [[b for b in i if c[b] > 2] for i in A] 


[['b', 'c'], ['b'], ['c', 'e'], ['c', 'e'], ['b', 'c', 'e']] 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: