modifying a list while iterating through

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Sun Feb 25 21:15:32 EST 2007


On Feb 25, 5:12 pm, dustin.g... at gmail.com wrote:
> consider the following working loop where Packet is a subclass of
> list, with Packet.insert(index, iterable) inserting each item in
> iterable into Packet at consecutive indexes starting at index.
>
>     i=0
>     while(i<len(packet)-4):
>         if packet[i:i+5]==Packet("01110"):
>             packet.insert(i, "01111")
>             i+=10 #skip the 5 bits inserted, and skip the 5 bits just
> checked bc overlap should not trigger insertion
>         else: i+=1
>
> is there a way to do this more elegantly?  seems like a big kludge.


If Packet consists of '0's and '1's, then it may be
easier to convert to, or base the class on str (strings):

packet = "1010101111011100111010001"
print "BEFORE ", packet
li = packet.split("01110")
packet = "0111001111".join(li)
print "AFTER  ", packet

--
Hope this helps,
Steven




More information about the Python-list mailing list