在 python 中对列表进行排序

2024-04-21

我的目标是对字符串列表进行排序,其中单词必须按字母顺序排序。除了以“s”开头的单词应该位于列表的开头(它们也应该排序),然后是其他单词。

下面的函数为我做到了这一点。

def mysort(words):
    mylist1 = sorted([i for i in words if i[:1] == "s"])
    mylist2 = sorted([i for i in words if i[:1] != "s"])
    list = mylist1 + mylist2
    return list

我只是在寻找替代方法来实现此目的,或者是否有人可以发现上述代码的任何问题。


你可以用一行来完成:

sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)

The sorted()函数接受关键字参数key,用于在比较完成之前转换列表中的值。

例如:

sorted(words, key=str.lower)
    # Will do a sort that ignores the case, since instead
    # of checking 'A' vs. 'b' it will check str.lower('A')
    # vs. str.lower('b').

sorted(intlist, key=abs)
    # Will sort a list of integers by magnitude, regardless
    # of whether they're negative or positive:
    # >>> sorted([-5,2,1,-8], key=abs)
    #     [1, 2, -5, -8]

我在排序时使用这样的翻译字符串的技巧:

"hello" => "bhello"  
"steve" => "asteve"

因此,在比较中“steve”会出现在“hello”之前,因为比较已经完成with the a/b prefix.

请注意,这仅影响用于比较的键,not排序出来的数据项。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 python 中对列表进行排序 的相关文章

随机推荐