Kaiye Yang
Kaiye Yang

Reputation: 21

Remove specific words within a list with over twice occurance python

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:```

Upvotes: 0

Views: 55

Answers (3)

SunStorm44
SunStorm44

Reputation: 71

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]

Upvotes: 0

j1-lee
j1-lee

Reputation: 13929

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]

Upvotes: 2

adhg
adhg

Reputation: 10853

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]

Upvotes: 1

Related Questions