如何在python中基于第2或第3按字母顺序排序句子列表Word之类的。
例子:
Input: ["The efgh ijk", "The abcd efgh", "The aab xyz"]
Output: ["The aab xyz", "The abcd efgh", "The efgh ijk"]
lst = ["The efgh ijk", "The abcd efgh", "The aab xyz"]
sort_lst = sorted(lst)
打印(sort_lst)
问题的基本标题:Sorting based on 2nd or 3rd word
您可以使用sorted
与lambda
和split()
,如下所示:
(这种方法首先考虑第二个单词,然后考虑第三个单词)
>>> lst = ["The efgh ijk" ,"The aab wxy", "The abcd efgh", "The aab xyz"]
>>> sorted(lst, key=lambda item: (item.split()[1], item.split()[2]))
['The aab wxy', 'The aab xyz', 'The abcd efgh', 'The efgh ijk']
>>> lst = ["The efgh ijk" ,"The aab wxy", "The abcd efgh", "The aab xyz", "abc efgh xyz"]
>>> sorted(lst, key=lambda item: (item.split()[1], item.split()))
['The aab wxy', 'The aab xyz', 'The abcd efgh', 'The efgh ijk', 'abc efgh xyz']