在python中排序列表

mis*_*ded 4 python sorting

我的目的是对字符串列表进行排序,其中单词必须按字母顺序排序.除了以"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
Run Code Online (Sandbox Code Playgroud)

我只是在寻找替代方法来实现这一点,或者任何人都可以找到上述代码的任何问题.

int*_*ger 8

可以在一行中完成

sorted(words, key=lambda x: 'a'+x if x[:1] == 's' else 'b'+x)
Run Code Online (Sandbox Code Playgroud)

或者:

sorted(words, key=lambda x: 'a'+x if x.startswith('s') else 'b'+x)
Run Code Online (Sandbox Code Playgroud)

(更具可读性.)

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]
Run Code Online (Sandbox Code Playgroud)

我在进行排序时使用了这样的翻译字符串:

"你好"=>"bhello"
"steve"=>"asteve"

所以"史蒂夫"会在"你好"之前出现


Ash*_*ary 5

1.你可以generator expression在里面使用sorted.

2.你可以用str.startswith.

3.不要list用作变量名.

4.key=str.lower在排序中使用.

mylist1 = sorted((i for i in words if i.startswith(("s","S"))),key=str.lower)
mylist2 = sorted((i for i in words if not i.startswith(("s","S"))),key=str.lower)
return mylist1 + mylist2
Run Code Online (Sandbox Code Playgroud)

为什么str.lower

>>> "abc" > "BCD"
True
>>> "abc" > "BCD".lower()  #fair comparison
False
Run Code Online (Sandbox Code Playgroud)