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

时间:2013-12-06 19:52:01

标签: python

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()

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

7 个答案:

答案 0 :(得分:5)

您可以使用words参数调用sortedkey进行排序,以“教导”sorted您希望words中的项目如何下令:

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

key中的每个项目调用words函数一次,并返回一个代理值,words中的项目将通过该代理值进行排序。 tuples,例如上面lambda函数返回的print(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])) # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] ,按照字典顺序排序(根据元组中的第一项,根据第二项断开关系)。

这项技术以及其他技术在优秀的Sorting Howto中进行了解释。


例如,

words

请注意,如果word[0]包含空字符串,则IndexError会引发''.startswith('x')。相比之下,False会返回word.startswith('x')。 因此,如果您希望front_x处理空字符串,请使用word[0] == 'x';如果您希望引发异常,请使用{{1}}。

答案 1 :(得分:2)

使用列表推导

list =  ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
list.sort()
listA = [item for item in list if item[0] == 'x']
listB = [item for item in list if item[0] != 'x']
listC = listA + listB

答案 2 :(得分:2)

这很有效,而且简单易懂。

def front_x(words):
    xlist = [item for item in words if item[0] =='x']
    nonXList = [item for item in words if item[0] !='x']
    xlist.sort() # The .sort() method sorts a list alphabetically 
    nonXList.sort()
    Combined_Lists = xlist + nonXList
    return Combined_Lists
    #You can also comment Combined_Lists and 
    #just have return xlist + nonXList

由于你是Python的新手,我试图让它变得尽可能简单。

答案 3 :(得分:1)

返回的错误是因为sort不返回值,它只是修改列表。

这似乎是一种相当快速的方法,它以线性时间运行,你不会比这更快。话虽如此,您可以使用内联代码来缩短它,但它并不总是更具可读性。

答案 4 :(得分:1)

>>> l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] 
>>> sorted ([x for x in l if x.startswith('x')]) + sorted([x for x in l if not x.startswith('x')])
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']

答案 5 :(得分:0)

return sorted([w for w in words if w[0] == 'x']) + sorted([w for w in words if w[0] != 'x'])

答案 6 :(得分:0)

错误是因为.sort()就位。它返回None,您无法执行None + None

由于Python的排序是稳定的,你也可以通过做两种

来实现这一点
>>> L = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
>>> sorted(sorted(L), key=lambda x:x[0]!='x')
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']

就地版

>>> L.sort()
>>> L.sort(key=lambda x:x[0]!='x')
>>> L
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']