Reputation: 2642
Input
['27', ' 5', '6', ' 0', ' 0', '', '', '', '','','','','','34','32','','','','']
I want my output to be something like this. The logic is to replace 4 consecutive duplicate empty strings ' ' with single new item while retaining the rest of the items.
['27', ' 5', '6', ' 0', ' 0', 'LOL','LOL', '34','32','LOL']
I'm confused as to why this only gives the output as
['LOL','LOL','LOL']
My code is as below:
from itertools import groupby,repeat
L = ['27', ' 5', '6', ' 0', ' 0', '', '', '', '','','','','','34','32','','','','']
grouped_L = [(k, len(list(g))) for k,g in groupby(L)]
final_list = [z if x=='' else x for x,y in grouped_L for z in repeat('LOL',(y//4)) ]
print(final_list)
Upvotes: 1
Views: 88
Reputation: 12890
Without list comprehensions but IMHO it is a much easier solution.
a = ['27', ' 5', '6', ' 0', ' 0', 'LOL', '34','32','LOL']
def remove_duplicates(w_duplicates):
wo_duplicates = []
for el in w_duplicates:
if wo_duplicates and el == wo_duplicates[-1]:
continue
wo_duplicates.append(el)
return wo_duplicates
print remove_duplicates(a)
Upvotes: 1
Reputation: 1122232
Your innermost loop produces no results for any y < 4
:
>>> from itertools import repeat
>>> y = 4
>>> list(repeat('LOL', y // 4))
['LOL']
>>> y = 3
>>> list(repeat('LOL', y // 4))
[]
With no iterations, nothing will be added to the resulting list.
You'll need to use a different strategy; you'll need to include LOL
for groups with length y
of 4 and up, and for everything else use the original, and always repeat:
[value
for x, y in grouped_L
for value in repeat(x if y < 4 else 'LOL', y if y < 4 else y // 4)]
So the above either includes x * y
for y < 4
, otherwise it'll include 'LOL' * (y // 4)
for anything else:
>>> [value
... for x, y in grouped_L
... for value in repeat(x if y < 4 else 'LOL', y if y < 4 else y // 4)]
['27', ' 5', '6', ' 0', ' 0', 'LOL', '34', '32', 'LOL']
Upvotes: 2