Sorting list of lists based on a given string in Python -
i have list of lists following:
list_of_lists = [ ('test_ss', 'test 1'), ('test_2_ss', 'test 2'), ('test_3_ss', 'test 3'), ('test_ss', 'test 4') ] i need sort list of lists first item in each list based on given variable string.
as example, want sort 'test_ss' resulting list of lists be:
sorted_list_of_lists = [ ('test_ss', 'test 1'), ('test_ss', 'test 4'), ('test_2_ss', 'test 2'), ('test_3_ss', 'test 3'), ] i've tried number of examples off , others (sorting list of lists based on list of strings, sorting lists based on particular element - python, sorting multiple lists based on single list in python, etc) haven't found right approach (or i've not been following examples correctly.
any pointers?
you can use simple key function this:
in [59]: def compare(element): ....: return element[0] == 'test_ss' or 99999 ....: in [60]: sorted(list_of_lists, key=compare) out[60]: [('test_ss', 'test 1'), ('test_ss', 'test 4'), ('test_2_ss', 'test 2'), ('test_3_ss', 'test 3')]
Comments
Post a Comment