按字母顺序排序列表,特殊情况下某些起始字母 [英] Sorting list by alphabetical order, with special case for certain starting letter
问题描述
给出一个字符串列表,我想返回一个按排序顺序排列的字符串列表,除了首先对所有以'x'开头的所有字符串进行分组.
Given a list of strings, I want to return a list with the strings in sorted order, except group all the strings that begin with 'x' first.
例如:
['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
应该产生:
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
我知道可以通过制作2个列表并在组合它们之前对每个列表进行排序来完成,但是我不确定如何编写以"x"为第一个字符的条件.
I know it can be done by making 2 lists and sorting each of them before combining them, but I'm not sure how to write the condition in which 'x' is the first character.
推荐答案
sorted
或 list.sort
接受可选 key
关键字参数.这是用于获取排序键的函数,并且该函数的返回值用于比较而不是原始项目.
sorted
or list.sort
accepts optional key
keyword argument. That is the function used to get sort key, and the return value of the function is used to compare instead of the original items.
>>> words = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
>>> sorted(words, key=lambda word: (word[0] != 'x', word))
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
使用的 word [0]!='x'
;返回单词的 False
(0)以 x
开头,其他单词的 True
(1)开头;结果单词以 x
开头.
used word[0] != 'x'
; which return False
(0) for word starts with x
, True
(1) for other words; resulting words start with x
come first.
这篇关于按字母顺序排序列表,特殊情况下某些起始字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!