Eric D. Brown D.Sc.
Eric D. Brown D.Sc.

Reputation: 1956

Sorting list of lists based on a given string in Python

I have a list of lists like the following:

list_of_lists = [
   ('test_ss', 'Test 1'),
   ('test_2_ss', 'Test 2'),
   ('test_3_ss', 'Test 3'),
   ('test_ss', 'Test 4')
]

I need to sort this list of lists by the first item in each list based on a given variable string.

As an example, I want to sort by 'test_ss' to the resulting list of lists would 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 a number of examples off SO and others (Sorting a list of lists based on a list of strings, Sorting lists based on a particular element - Python, sorting multiple lists based on a single list in python, etc) but haven't found the right approach (or I've just not been following those examples correctly.

Any pointers?

Upvotes: 1

Views: 309

Answers (3)

karakfa
karakfa

Reputation: 67567

this will do

tuples = [
   ('test_ss', 'Test 1'),
   ('test_2_ss', 'Test 2'),
   ('test_3_ss', 'Test 3'),
   ('test_ss', 'Test 4')
]

sorted(tuples, key=lambda x: x[0].replace('test_ss','test_ _ss'))

[('test_ss', 'Test 1'),
 ('test_ss', 'Test 4'),
 ('test_2_ss', 'Test 2'),
 ('test_3_ss', 'Test 3')]

you want to treat 'test_ss' semantically as the smallest element in sorting order but it's not in textual representation. key.replace(..) handles it.

Upvotes: 0

Sede
Sede

Reputation: 61293

You can use a simple key function like 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')]

Upvotes: 2

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24164

If you want to partition, just return False if the string matches:

>>> sorted(list_of_lists, key=lambda value: value[0] != 'test_ss')
[('test_ss', 'Test 1'),
 ('test_ss', 'Test 4'),
 ('test_2_ss', 'Test 2'),
 ('test_3_ss', 'Test 3')]

Upvotes: 1

Related Questions