![](/img/trans.png)
[英]How can I sort DataFrame in Python on 1st variable in ascending, on 2nd variable in custom order and on 3rd variable in Descending
[英]How can I sort a list for sentence alphabetically in python based on 2nd or 3rd word or something like that
如何根据第二个或第三个单词或类似的东西在 python 中按字母顺序对句子列表进行排序。
例子:
Input: ["The efgh ijk", "The abcd efgh", "The aab xyz"]
Output: ["The aab xyz", "The abcd efgh", "The efgh ijk"]
lst = ["efgh ijk", "abcd efgh", "aab xyz"]
sort_lst = 排序(lst)
打印(sort_lst)
问题的基本标题: Sorting based on 2nd or 3rd word
您可以使用lambda
和split()
sorted
,如下所示:
(这种方法首先考虑第二个词然后第三个词)
>>> 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.