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]
To remove elements from ArrayList based on a condition or predicate or filter, use removeIf() method. You can call removeIf() method on the ArrayList, with the predicate (filter) passed as argument. All the elements that satisfy the filter (predicate) will be removed from the ArrayList.
To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.
In Python remove() will remove the first occurrence of value in a list.
The methods are remove(), pop() and clear(). It helps to remove the very first given element matching from the list. The pop() method removes an element from the list based on the index given. The clear() method will remove all the elements present in the list.
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']]
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With