find sublist inside list
MRAB
google at mrabarnett.plus.com
Mon May 4 11:09:16 EDT 2009
Matthias Gallé wrote:
> bearophileHUGS at lycos.com wrote:
>> John O'Hagan:
>>> li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
>>> for i in range(len(li)):
>>> if li[i:i + 2] == ['a', 'c']:
>>> li[i:i + 2] = ['6']
>>
>> Oh well, I have done a mistake, it seems.
>> Another solution then:
>>
>>>>> 'acaccgac'.replace("ac", chr(6))
>> '\x06\x06cg\x06'
>>
>> Bye,
>> bearophile
>
> Thanks bearophile and John for your quick answers.
> Unfortunately, the int that can replace a sublist can be > 255, but
> John's answer looks simple and good enough for me. I will use it as a
> starting point.
>
John's solution changes the length of the list over which it's
iterating.
I'd suggest something more like:
li = ['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
pos = 0
try:
while True:
pos = li.index('a', pos)
if li[pos : pos + 2] == ['a', 'c']:
li[pos : pos + 2] = [6]
pos += 1
except ValueError:
pass
More information about the Python-list
mailing list