Deleting elements of a list based on a condition

Before you add a new key to the dictionary, you have to check if the key exists. If not, just add the key to the dictionary. Otherwise, update the key's value.

A = [['a','b','c'],['b','d'],['c','d','e'],['c','e','f'],['b','c','e','g']]
word_count = {}
for i in range(len(A)):
  for words in A[i]:
    if words not in word_count:
      word_count[words] = 0
    word_count[words] += 1

Then filter the initial list using the created dictionary.

B = [[x for x in A[i] if word_count[x] > 2] for i in range(len(A))]
print(B)

Output

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

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]

Output:

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

Tags:

Python

List