[Tutor] list comprehension, testing for multiple conditions

Pete O'Connell pedrooconnell at gmail.com
Wed Aug 22 11:51:07 CEST 2012


What a great mailing list!
Thanks for all the responses.
I have a few questions, though, first in regards to Puneeth's code. He
writes to use:

>theTextAsListNoVnOrVtOrEmptyLine = [x for x in theTextAsListStripped if "vn" not in x  and "vt" not in x and x!= ""]

It works but what I don't understand about this line is why the ands
are nor ors ("or" doesn't work even though I would have expected it
to)
I am sure I will have a few more questions over the next couple days
as I work my way through the responses.

Thanks
Pete



On Wed, Aug 22, 2012 at 6:23 PM, Puneeth Chaganti <punchagan at gmail.com> wrote:
> On Wed, Aug 22, 2012 at 11:35 AM, Pete O'Connell
> <pedrooconnell at gmail.com> wrote:
>> Hi I am trying to parse a text file and create a list of all the lines
>> that don't include: "vn", "vt" or are empty. I want to make this as
>> fast as possible because I will be parsing many files each containing
>> thousands of lines. I though I would give list comprehensions a try.
>> The last 3 lines of the code below have three list comprehensions that
>> I would like to combine into 1 but I am not sure how to do that.
>> Any tips would be greatly appreciated
>>
>> pete
>>
>> #start############################################################
>> fileName = '/usr/home/poconnell/Desktop/objCube.obj'
>> theFileOpened = open(fileName,'r')
>> theTextAsList = theFileOpened.readlines()
>>
>> theTextAsListStripped = []
>> for aLine in theTextAsList:
>>
>>     theTextAsListStripped.append(aLine.strip("\n"))
>>
>> theTextAsListNoVn = [x for x in theTextAsListStripped if "vn" not in x]
>> theTextAsListNoVnOrVt = [x for x in theTextAsListNoVn if "vt" not in x]
>> theTextAsListNoVnOrVtOrEmptyLine = [x for x in theTextAsListNoVn if x != ""]
>
> Something like this should work :
>
> theTextAsListNoVnOrVtOrEmptyLine = [x for x in theTextAsListStripped
> if "vn" not in x  and "vt" not in x and x!= ""]
>
> HTH,
> Puneeth



-- 
-


More information about the Tutor mailing list