Replace sequence in list with a value in Python

I want to replace example two specific one-after-one going elements in a list with another element (elements). For example - replace ["+", "="] with ["+="]:

Input:

[3, "blah", "+", "foo", "=", "+", "="]

Output:

[3, "blah", "+", "foo", "=", "+="]

Answers


The following, though very inefficient for long lists this will work:

loop=[3, "blah", "+", "foo", "=", "+", "="]
out=[]
prevdone=False
for i in range(len(loop)):
    if loop[i]=="+" and loop[i+1]=="=":
        out.append("+=")
        prevdone=True
    elif not(prevdone):
        out.append(loop[i])
    else:
        prevdone=False
print(out)

It iterates through the list and checks if the current and following characters meet conditions. If they do, it will add += and skip the next item.

I have considered using "".join(list) and string.split("") but that wouldn't (I don't think) work for multiple-character elements.

As for a general function, it could be modified as such:

def loopReplace(loopList, item1, item2):
    out=[]
    prevdone=False
    for i in range(len(loopList)):
        if loopList[i]==item1 and loopList[i+1]==item2:
            out.append(str(item1)+str(item2))
            prevdone=True
        elif not(prevdone):
            out.append(loopList[i])
        else:
            prevdone=False
    return out

Need Your Help

What will passing a Dictionary into Controller.Json return?

.net asp.net-mvc json

Let's say I have a Dictionary<string,object> like so:

Why does Netbeans know my full name and email?

netbeans ide

Serious question: I just committed to github and got shocked: Netbeans has transferred my full name and my PRIVATE EMAIL ADRESS (which i never never never ever use in IDEs, websites etc) to github ...