Start learning free

LESSON 24 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V4 in Python: Sort by a Column with a key lambda

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

def sortLines(self, lines: List[str], field: int) -> str:

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Use sorted with a key lambda that splits each line on "," and returns the field - 1 element. Python's sorted is stable by default.

The full solution:
class Solution:
    def sortLines(self, lines, field):
        sortedLines = sorted(lines, key=lambda l: l.split(",")[field - 1])
        return "\n".join(sortedLines)

STEP 1 OF 2
    Ctrl + Enter to check

    PYTHON · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in Python, explained

    Problem overview

    This version adds the effect of sort -t, -k N,N -s. Each line is comma-separated and has at least field fields; a field may be empty, as in "a,,c". Given a 1-indexed field, sortLines sorts the lines stably by that field, compared as strings by character code, and returns the original lines joined by "\n".

    With field = 2 and ["alice,30", "bob,25", "carol,40"] the keys are "30", "25" and "40", so the result is "bob,25\nalice,30\ncarol,40". Lines whose fields are equal keep their input order, and an empty list gives the empty string.

    Approach: sort whole lines by a piece of each line

    The output contains the full lines, but the order depends on one part of each. That is the job of the key argument of sorted: it computes a sort key from each element and compares the keys, while the elements themselves are returned. Here the key is the chosen field of the line.

    To extract the field, split the line at commas with l.split(","), which gives a list of strings, and take the item at position field - 1. Fields count from 1 but list positions count from 0, so field 2 is position 1.

    Step by step

    1. Create sortedLines from sorted with a key that is a lambda: take a line, split it at commas, return the piece at field - 1.
    2. Return the sorted lines joined with a newline between each two.

    The solution in Python

    class Solution:
        def sortLines(self, lines, field):
            sortedLines = sorted(lines, key=lambda l: l.split(",")[field - 1])
            return "\n".join(sortedLines)
    

    Notes on the details:

    • The lambda uses field from the surrounding method. Python lambdas can read variables of the enclosing function, so no extra parameter is needed.
    • "a,,c".split(",") keeps the empty field in the middle, giving three pieces, so the position arithmetic stays correct. An empty key is the smallest string and sorts first.
    • Ties are resolved by sorted's stability: lines with equal keys stay in their input order, which is what -s asks for. No tiebreaker is needed or allowed here, since the real command with -s does not compare the rest of the line.
    • Keys are compared as strings. If a key contains digits, they sort as text.

    Complexity

    The time is O(n log n) comparisons for n lines, plus one split per line; Python computes each key once. The extra space is O(n) for the sorted list and the keys.

    Edge cases and common mistakes

    linesfieldresult
    ["alice,30", "bob,25", "carol,40"]2"bob,25\nalice,30\ncarol,40"
    ["alice,30", "bob,25", "carol,40"]1"alice,30\nbob,25\ncarol,40"
    ["x,b", "y,a", "z,b", "w,a"]2"y,a\nw,a\nx,b\nz,b"
    ["a,,c", "b,x,d", "c,,e"]2"a,,c\nc,,e\nb,x,d"
    ["a,100", "b,20", "c,3"]2"a,100\nb,20\nc,3"
    • In the third row, "y,a" precedes "w,a" because it came first in the input, even though "w" is smaller than "y". Likewise "x,b" stays before "z,b".
    • In the fourth row, the two empty fields tie and keep input order, ahead of "x".
    • In the last row the keys are compared as text, so "100" comes before "20". Converting the key with int would be wrong for this version.
    • Using field instead of field - 1 as the index is the classic off-by-one: with field = 2 it reads the third piece, and fails with an IndexError when the lines have only two fields.
    • Don't sort by the whole line as a tiebreaker. The statement wants ties kept in input order.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free