Skip to main content
 首页 » 编程设计

python之按条件条件对列表进行排序

2025年05月04日23arxive

我知道如何使用 sort() 方法和适当的 lambda 规则在 Python 中简单地对列表进行排序。但是我不知道如何处理以下情况:

I have a list of strings, that either contain only letters or contain a specific keyword and a number. I want to sort the list first so as to put the elements with the keyword at the end, then sort those by the number they contain.

例如我的列表可能是:mylist = ['abc','xyz','keyword 2','def','keyword 1'] 我希望它排序为 ['abc' ,'def','xyz','关键字 1','关键字 2']。

我已经有了类似的东西

mylist.sort(key=lambda x: x.split("keyword")[0],reverse=True) 

只产生

['xyz', 'def', 'abc', 'keyword 2', 'keyword 1'] 

请您参考如下方法:

一个衬垫解决方案:

mylist.sort(key=lambda x: (len(x.split())>1, x if len(x.split())==1 else int(x.split()[-1]) ) ) 

解释: 第一个条件 len(x.split())>1 确保多词串位于单词串之后,因为它们可能有数字。因此,由于第一个条件,现在仅在单字串与单字串或多字串与多字串之间存在联系。请注意,多字串和单字串不会有任何关系。因此,如果多字字符串我返回一个整数,否则返回字符串本身。

示例:

['xyz', 'keyword 1000', 'def', 'abc', 'keyword 2', 'keyword 1']

结果:

>>> mylist=['xyz', 'keyword 1000', 'def', 'abc', 'keyword 2', 'keyword 1'] 
>>> mylist.sort(key=lambda x: (len(x.split())>1, x if len(x.split())==1 else int(x.split()[-1]) ) ) 
>>> mylist 
['abc', 'def', 'xyz', 'keyword 1', 'keyword 2', 'keyword 1000']