Skip to content Skip to sidebar Skip to footer

Unpacking A Split Inside A List Comprehension

If I want to generate a list of tuples based on elements of lines of a document, i can do : [(line.split()[0], line.split()[-1][3:8]) for line in open('doc.txt')] for example

Solution 1:

You can use map (python3) or itertools.imap (python2) over open:

[(line[0], line[-1][3:8]) for line in map(str.split, open("doc.txt"))]

or use a generator:

[(line[0], line[-1][3:8]) for line in ( l.split() for l in open("doc.txt"))]  

Solution 2:

You can use map with the unbound method str.split:

[(linesplit[0], linesplit[-1][3:8]) for linesplit in map(str.split, open("doc.txt"))]

However I'd stay away from these; I'd instead use a generator:

defread_input(filename):
    withopen(filename) as f:
        for line in f:
            parts = line.split()
            yield parts[0], parts[-1][3:8]

It might be a bit more, but it is easier to follow - and readability counts - and the user has a choice between using read_input('doc.txt') as such, or wrapping it into a list if needed.

Post a Comment for "Unpacking A Split Inside A List Comprehension"