Skip to main content
 首页 » 编程设计

python之有没有更短的方法来实现这个功能

2025年05月04日13cmt

B. front_x 给定一个字符串列表,返回一个按排序顺序排列的字符串列表,除了首先将所有以 'x' 开头的字符串分组。例如['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] 产生 ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] 提示:这可以通过制作 2 个列表并在合并之前对每个列表进行排序。

def front_x(words): 
  xList = [] 
  nonXList = [] 
  for word in words: 
    if word[0] == 'x': 
      xList.append(word) 
    else: 
      nonXList.append(word) 
  return sorted(xList) + sorted(nonXList) 

我是 python 和一般编程的新手,但我觉得有一种更紧凑的方式来编写这段代码,还是有一种更“pythonic”的方式?

我也尝试返回行:

return xlist.sort() + nonXList.sort() 

但这错了。为什么会这样?

请您参考如下方法:

您可以通过一次调用 sorted 来对 words 进行排序,使用 key 参数来“教” sorted 如何排序您希望订购 words 中的项目:

def front_x(words): 
    return sorted(words, key=lambda word: (word[0] != 'x', word)) 

key 函数对 words 中的每个项目调用一次,并返回一个代理值,words 中的项目将根据该代理值进行排序. 元组,例如上面的 lambda 函数返回的元组,按字典顺序排序(根据元组中的第一项,并根据第二项打破平局) .

这项技术以及其他技术在优秀的 Sorting Howto 中有解释。 .


例如,

print(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])) 
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] 

请注意,如果 words 包含空字符串,word[0] 将引发 IndexError。相反,''.startswith('x') 返回 False。 因此,如果您希望 front_x 处理空字符串,请使用 word.startswith('x'),并使用 word[0] == 'x' 如果您想引发异常。