你可以用一行来完成:
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排序出来的数据项。