我有一个如下所示的列表:
list_of_lists = [
('test_ss', 'Test 1'),
('test_2_ss', 'Test 2'),
('test_3_ss', 'Test 3'),
('test_ss', 'Test 4')
]
我需要根据给定的变量字符串按每个列表中的第一项对这个列表列表进行排序。
举个例子,我想按“test_ss”对结果列表进行排序:
sorted_list_of_lists = [
('test_ss', 'Test 1'),
('test_ss', 'Test 4'),
('test_2_ss', 'Test 2'),
('test_3_ss', 'Test 3'),
]
我已经尝试了一些SO和其他示例( 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 等),但没有找到正确的方法(或者我只是没有正确遵循这些示例.
有什么指点吗?
最佳答案
您可以使用像这样的简单按键功能:
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')]
关于python - 根据Python中给定的字符串对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34621440/