views:

141

answers:

1

I need to identify some locations in a file where certain markers might be. I started off thinking that I would use list.index but I soon discovered that returns the first (and only the first) item. so I decided to implement my own solution which was

count=0
docIndex=[]
for line in open('myfile.txt','r'):
    if 'mystring' in line:
        docIndex.append(count)
    count+=1

But this is Python right. There has to be a simpler solution since well it is Python. Hunting around this site and the web I came up with something slightly better

newDocIndex=[]
for line in fileinput.input('myfile',inplace=1):
    if 'mystring' in line:
 newDocIndex.append(fileinput.lineno())

I know this is too much info but since I finished grading finals last night I thought well-this is Python and we want to make some headway this summer-lets try a list comprehension

so I did this:

[fileinput.lineno() for line in fileinput.input('myfile',inplace=1) if 'mystring' in line]

and got an empty list. So I first guessed that the problem is that the item in the for has to be the item that is used to build the list. That is if I had line instead of fileinput.lineno() I would have had a non-empty list but that is not the issue.

Can the above process be reduced to a list comprehension?

Using the answer but adjusting it for readability

listOfLines=[lineNumb for lineNumb,dataLine in enumerate(open('myfile')) if 'mystring' in dataLine]
+7  A: 

What about this?

[index for index,line in enumerate(open('myfile.txt')) if 'mystring' in line]
sykora
Thanks, unless I did something wrong no
PyNEwbie
no what? it does exactly what your code does in a nice pythonic manner.
SilentGhost
I did somethinng wrong wow it worked thanks
PyNEwbie
This solution is why I don't particularly care for list comprehensions. They are incomprehensible. I say that tongue in cheek, but really, why is this considered "better" than something more straight-forward?
Bryan Oakley
I am learning that they are actually easier to read. I would have agreed with you six months ago. I am going to make an edit and see if that is not easier to read
PyNEwbie
Whoops I can't edit the answer look at my question I will add my suggested edit to the end of the question
PyNEwbie
@Bryan: they are straight forward! as for why it's better you can "import this".
SilentGhost
some newlines and indents would make the comprehension easier to read, and not easier to understand than any other method I can think of.
Aaron Watters
whoops: above "not easier" replace "not harder"
Aaron Watters
@Bryan Oakley: For one, List Comprehensions are faster than using the corresponding for loop to do the same thing. Secondly, how is this incomprehensible? They are concise yet have the same expressiveness as the for-loop. The only hard parts could be: a) enumerate() and b) the tuple assignment - Otherwise, it's pretty easy to pick up.
sykora