Search code examples
pythonlistsortingalphanumeric

Sort List in Alphanumeric Order


I'm trying to sort a list after zip.

list_sort = zip(l1, l2)

l1 = ['F2', 'G2', 'A10', 'H2', 'A3', 'E3', 'B10', 'C1', 'D1', 'E1', 'D2', 'C11', 'A1']
l2 = [40, 40, 90, 90, 90, 90, 90, 120, 120, 120, 120, 120, 90]

I'm looking to sort l1 in this order:

l1 = ['A1', 'C1', 'D1', 'E1', 'D2', 'F2', 'G2', 'H2', 'A3', 'E3', 'A10', 'B10', 'C11']

l2 will sort with l1.

l2 = [90, 120, 120, 120, 120, 40, 40, 90, 90, 90, 90, 90, 120]

What I have tried:

list(sorted(list_sort, key=lambda item: (item[0][1], item[0][1:0])))

Solution

  • It looks like you want to sort by 2 criteria: first, by the value of the number at the end of the string, and then by the starting letter.

    It seems like you swapped the order of your criteria, and you also have [1:0] as your indexing to obtain the value of the number, which has an exclusive-end index of 0 which will result in an empty string.

    Instead, you want to first sort by the number following the first character of the string. You can get the string value of this via item[1:], and then apply int(item[1:]) to cast it to a number. Then, your second criteria is just the first character itself (which for your list is always a letter), which can be obtained via item[0]

    So, your new key would be (int(item[1:]), item[0]).

    To sort zip(l1, l2) by these criteria, the following should give you your desired output:

    zipped = zip(l1, l2)
    sorted_zip = sorted(zipped, key=lambda item: (int(item[0][1:]), item[0][0]))
    

    This will sort the zipped list by the criteria for l1, since the corresponding l1 entry is obtained by item[0] for an entry item in the zipped list. Then, if you want to unzip from this:

    sorted_l1 = [item[0] for item in sorted_zip]
    sorted_l2 = [item[1] for item in sorted_zip]