Home > Net >  Remove specific words within a list with over twice occurance python
Remove specific words within a list with over twice occurance python

Time:07-15

Here is a list A=[1,1,1,2,2,2,4,5,6,6,7,7,7]

Can we have an algorithm that modifies all the numbers that occur more than twice to be maximized twice in list A?

e.g. list new_A=[1,1,2,2,4,5,6,6,7,7]

I have tried the conditions to separate:

    if Counter(list A)[num]>2:```

CodePudding user response:

You can do something like this:

from collections import Counter

max_accurance =2
list_A=[1,1,1,2,2,2,4,5,6,6,7,7,7]

d = dict(Counter(list_A))

new_list=[]
for k,v in d.items():
    if v>=max_accurance:
        new_list.extend([k]*max_accurance)
    else:
        new_list.append(k)

output

[1, 1, 2, 2, 4, 5, 6, 7, 7]

CodePudding user response:

You can use groupby and islice:

from itertools import groupby, islice

lst = [1,1,1,2,2,2,4,5,6,6,7,7,7]

output = [x for _, g in groupby(lst) for x in islice(g, 2)]
print(output) # [1, 1, 2, 2, 4, 5, 6, 6, 7, 7]

CodePudding user response:

Most compressed way I could think of:

import operator as op

A=[1,1,1,2,2,2,4,5,6,6,7,7,7]
B = []

for elem in set(A):
    B.extend([elem, elem]) if op.countOf(A, elem) > 2 else B.extend([elem])

Output:

[1, 1, 2, 2, 4, 5, 6, 7, 7]
  • Related