pythonlistsortingalphabetical-sort

Python Alphabetical Sorting 2D list not working


I have a list with 4 columns:

L = [[0, '0000000', 'Hashfunction.jpg', 258883, '.jpg'],
     [1, '0000001', 'a_test_grey.jpg', 24186, '.jpg'],
     [2, '0000002', 'b_test_grey.jpg', 4256, '.jpg'],
     [3, '0000003', 'IMG_20210323_062719.jpg', 6704108, '.jpg']]

This list I have to order alphabetically according to the 3rd column, the name of the files. I've tried different methods, but I'am still not successful.

Method 1:

sorted(L,key=lambda x:x[2])

results in:

[[0, '0000000', 'Hashfunction.jpg', 258883, '.jpg'],
 [3, '0000003', 'IMG_20210323_062719.jpg', 6704108, '.jpg'],
 [1, '0000001', 'a_test_grey.jpg', 24186, '.jpg'],
 [2, '0000002', 'b_test_grey.jpg', 4256, '.jpg']]

=> which is not correct!

Method 2:

sorted(L, key=operator.itemgetter(2))

results in:

[[0, '0000000', 'Hashfunction.jpg', 258883, '.jpg'],
 [3, '0000003', 'IMG_20210323_062719.jpg', 6704108, '.jpg'],
 [1, '0000001', 'a_test_grey.jpg', 24186, '.jpg'],
 [2, '0000002', 'b_test_grey.jpg', 4256, '.jpg']]

=> which is also not correct! Usually the file with the name 'a_test_grey.jpg' should be the first in the result!

When I change the sorting parameter, the column index in the commands from 2 to 0,1,3 the sorting is working correct according to the columns index. But the alphabetically sorting of column[2] is not working!

What's wrong in the command?


Solution

  • String comparison uses the ASCII table, so uppercase and lowercase come one set after the other. So all uppercase always compare to less than lowercase.

    Convert to lowercase (or alternatively, uppercase) everything when giving the key if that is what you want:

    L = [[0, '0000000', 'Hashfunction.jpg', 258883, '.jpg'],
         [1, '0000001', 'a_test_grey.jpg', 24186, '.jpg'],
         [2, '0000002', 'b_test_grey.jpg', 4256, '.jpg'],
         [3, '0000003', 'IMG_20210323_062719.jpg', 6704108, '.jpg']]
    
    print(sorted(L, key=lambda x: x[2].lower()))
    # >>> [[1, '0000001', 'a_test_grey.jpg', 24186, '.jpg'], [2, '0000002', 'b_test_grey.jpg', 4256, '.jpg'], [0, '0000000', 'Hashfunction.jpg', 258883, '.jpg'], [3, '0000003', 'IMG_20210323_062719.jpg', 6704108, '.jpg']]