我的目标是对一个字符串列表进行排序,其中必须对单词进行排序alphabetically.Except以"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我只是在寻找替代的方法来实现这一点,或者如果任何人可以发现上述代码的任何问题。
发布于 2013-07-12 13:59:02
您可以在一行代码中完成,如下所示:
sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)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”之前,因为比较是用a/b前缀完成的。
请注意,这只会影响用于比较的键,而不会影响排序出来的数据项。
发布于 2013-07-12 13:54:04
1.您可以在sorted中使用generator expression。
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为什么选择str.lower
>>> "abc" > "BCD"
True
>>> "abc" > "BCD".lower() #fair comparison
False发布于 2013-07-12 13:58:34
>>> l = ['z', 'a', 'b', 's', 'sa', 'sb', '', 'sz']
>>> sorted(l, key=lambda x:(x[0].replace('s','\x01').replace('S','\x01') if x else '') + x[1:])
['', 's', 'sa', 'sb', 'sz', 'a', 'b', 'z']出于排序的目的,这个键函数将每个以S或s开头的值替换为一个\x01,它优先于其他所有内容进行排序。
https://stackoverflow.com/questions/17608210
复制相似问题