I am trying to insert 'a' into filesContent list whenever there is an '>' in the element. The code below succeeds in insert an 'a' element after '>' except for the last 2 '>' elements. I don't understand why.
def specialparseFile(fname):
filesContent = list()
with open(fname) as f:
lines = [i.strip() for i in f]
lines = [line for line in lines if line]
for i in lines:
filesContent.append(i)
for x in range(len(filesContent)):
if '>' in filesContent[x]:
filesContent.insert(x + 1, 'a')
print(filesContent)
return filesContent
答案 0 :(得分:2)
Say for example your filesContent
is l
:
l = ['>', 'b', '>']
It has length 3, so your for loop would loop through indices 0, 1 and 2. After index 0 the array would be:
l = ['>', 'a', 'b', '>']
Now you can see your issue, the last >
will never be reached as it is at index 3.
You can loop backwards instead to resolve this:
range(len(filesContent) - 1, -1, -1)
Or if you prefer:
reversed(range(len(filesContent)))
Now looping through 2, 1, 0, after the first iteration you will have:
l = ['>', 'b', '>', 'a']
With the next index being 1, it is clear that the previous addition wont effect the list that still has to be looped through.
答案 1 :(得分:2)
The root cause of your bug has been well-explained in @Nick A's answer, another way is to remove for
loop and forget the index of list at all, by using the following code:
def specialparseFile(fname):
with open(fname) as f:
lines = filter(None, map(lambda x: x.strip(), f))
result = [[l, 'a'] if '<' in l else [l] for l in lines]
return sum(result, []) # flatten the nested list generated by previous line of code
答案 2 :(得分:0)
you can also do both in the same loop
...
for item in lines:
filesContent.append(item)
if ">" in item:
filesContent.append( "a" )