[Tutor] list comprehension, testing for multiple conditions

Pete O'Connell pedrooconnell at gmail.com
Fri Aug 24 03:11:45 CEST 2012


Hi, I have tried to simplify things and am running into a bit of trouble.
What i am really trying to do is: Keep all the lines starting with "v " and
then delete those lines whose modulus 5 don't equal zero

I have written it like this which seems to take a really long time (a
couple of  minutes when iteration over a folder with 200 files to parse)
#####################################
with open(theFilePath) as lines:
    #keep only the lines beginning with "v " (this works)
    theGoodLines = [line.strip("\n") for line in lines if "v " ==
line[0:2]]
    theLinesAsListSubset = []
    for i in range(len(theGoodLines)):
        nuke.tprint(i)
        if i%5 != 0:
            continue
        elif i%5 == 0:
            theLinesAsListSubset.append(theGoodLines[i])
########################################

I think it would be better to include the modulud test within the original
list comprehension but I am not sure how to access the index of "line":
    #something like this is a sketch of what I mean (I know it's wrong)
    theGoodLines = [line.strip("\n") for line in lines if "v " ==
line[0:2] and line.getIndex() % 5 == 0]


Do I need enumerate for this maybe?
Thanks
Pete
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120824/b7aa60d6/attachment.html>


More information about the Tutor mailing list