python - 根据Python中给定的字符串对列表进行排序

标签 python list sorting

我有一个如下所示的列表:

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 stringsSorting lists based on a particular element - Pythonsorting 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/

相关文章:

python - 如何在Python中有效地搜索和访问数据框中的某些单元格?

python - lambda 内的 lambda

python - 在 Python 模块中初始化静态列表的最佳方法

java - 对两个 ArrayList 中的元素进行排序和交换 (Java)

python - 在pygame中转换图像

python - 在 Python 的子列表中查找单词序列

python - 将数据从 neo4j 导出到 csv 而不是 json

amazon-web-services - 如何在 aws-amplify 中的列表查询中的字段上按日期(createdAt)排序?

C 尝试在数组中搜索特定数字

python - Datadog 计数指标因多个容器而下降