An effective way to make these python list understandings

advertisements

I had this original piece of code:

for x in rawFile:
    line += 1
    if line%2 == 0:
        self.newList.append(x.rstrip())
        self.timeStamp.append('0')

Then I saw how ugly it was and wanted to get it done with list comprehensions, hence I rewrote it as:

self.newList = [x[1].rstrip() for x in enumerate(rawFile) if x[0]%2 == 0]
self.timeStamp = ['0' for x in self.newList[]]

While the second one definitely seems more 'pythonic' to me, I still dislike the fact that I actually had to perform one extra iteration. This may be a nutty question, but does anyone know of a way where I can get this comprehension done in one iteration/line, more efficiently?


Try this:

self.newList, self.timeStamp = zip(*((x.rstrip(), '0') for i, x in enumerate(rawFile) if i%2==0))

Can't say anything about efficiency, but it is a one liner.