5
\$\begingroup\$

I'm trying to write a function that given a TSV file will get the maximum line length found in a column. I currently have this (working) function. However, I feel that I am missing something as this solution feels poor compared to solutions I have seen to find the maximum length of a file:

max(open(filename), key=len)

Anyway, I would love some feedback and would love some tough feedback.

def get_longest_item_in_tsv_column(filepath, column):
    '''
    Returns the longest line in a given file.
    '''

    longest_item = None

    with open(filepath, 'r') as f:
        csv_reader = csv.reader(f,
                                delimiter='\t')

        for row in csv_reader:

            current_item_length = len(row[column])

            if current_item_length > longest_item:
                longest_item = current_item_length
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

This code can be recast into something that will be more efficient if all you are doing is scanning the file for the length of the longest line:

longest_item = None
for row in csv_reader:
    current_item_length = len(row[column])
    if current_item_length > longest_item:
        longest_item = current_item_length

Can be replaced with this:

longest_item = max((len(r[column]) for r in csv_reader))

So, what did we build here? Working from the inside out:

len(r[column])

will return the length of the column in r. While

(len(r[column]) for r in csv_reader)

produces a generator which can return all of the lengths of column returned by csv_reader. And finally:

max((len(r[column]) for r in csv_reader))

returns the largest value of all of the column lengths.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.