I can't solve the following problem.
I have a list and items in it. I need to find 3 or more consecutive items and change them.
For example:
mylist = ["BLUE", "BLUE", "RED", "RED", "RED", "RED", "BLACK", "RED", "RED"]
Required output:
mylist = ["BLUE", "BLUE", "WHITE", "WHITE", "WHITE", "WHITE", "BLACK", "RED", "RED"]
There were 4 items found "RED" and changed to "WHITE". Less than 3 "RED" items are unchanged. There may be an elegant solution, but I still can't find it.
Will anyone help?
CodePudding user response:
You can use itertools.groupby
for the task:
from itertools import groupby
mylist = ["BLUE", "BLUE", "RED", "RED", "RED", "RED", "BLACK", "RED", "RED"]
out = []
for v, g in groupby(mylist):
g = sum(1 for _ in g)
out.extend(["WHITE" if g > 2 else v] * g)
print(out)
Prints:
['BLUE', 'BLUE', 'WHITE', 'WHITE', 'WHITE', 'WHITE', 'BLACK', 'RED', 'RED']
CodePudding user response:
I finally created this code. But there are not as many Pythonics as from Andrej Kesely. Thanks!
mylist = ["BLUE", "BLUE", "RED", "RED", "RED", "RED", "BLACK", "RED", "RED"]
counter = 0
for i in range(len(mylist)):
if mylist[i] == "RED":
counter = 1
if counter >= 3:
for k in reversed(range(counter)):
mylist[i-k] = "WHITE"
else:
counter = 0
print(mylist)