[Tutor] list comprehension, testing for multiple conditions
Peter Otten
__peter__ at web.de
Wed Aug 22 13:25:07 CEST 2012
Pete O'Connell wrote:
[Please don't to-post. Clip all text of previous posts except the portion
relevant to your question]
> Hi. The next step for me to parse the file as I want to is to change
> lines that look like this:
> f 21/21/21 22/22/22 24/24/23 23/23/24
> into lines that look like this:
> f 21 22 23 24
>
> Below is my terribly slow loop for doing this.
I'd say you are not yet at the point where you should care for speed too
much. Build the complete tool-chain with tests to verify correctness and
then measure execution time to find the bottlenecks.
> Any suggestions about
> how to make this code more efficient would be greatly appreciated
>
>
################################################################################
> fileName = '/usr/home/poconnell/Desktop/objCube.obj'
>
> with open(fileName) as lines:
> theGoodLines = [line.strip("\n") for line in lines if "vn" not in
> line and "vt" not in line and line != "\n"]
>
> for i in range(len(theGoodLines)):
> if theGoodLines[i][0] == "f":
> aGoodLineAsList = theGoodLines[i].split(" ")
> theGoodLines[i] = aGoodLineAsList[0] + " " +
> aGoodLineAsList[1].split("/")[-1] + " " +
> aGoodLineAsList[2].split("/")[-1] + " " +
> aGoodLineAsList[3].split("/")[-1] + " " +
> aGoodLineAsList[4].split("/")[-1]
>
> for anItem in theGoodLines:
> print anItem
If your sample data is representative you don't need most of the filtering:
fileName = ...
with open(fileName) as lines:
for line in lines:
if line.startswith("f "):
print " ".join(part.rpartition("/")[-1] for part in
line.split())
More information about the Tutor
mailing list