Is there a shorter way to make this function?

后端 未结 7 987
鱼传尺愫
鱼传尺愫 2021-01-24 23:47

B. front_x Given a list of strings, return a list with the strings in sorted order, except group all the strings that begin with \'x\' first. e.g. [\'mix\', \'xyz\', \'apple\',

7条回答
  •  情深已故
    2021-01-25 00:23

    The error is because .sort() is in-place. It returns None, and you can't do None + None

    Since Python's sort is stable, you can also accomplish this by doing two sorts

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

    And the in-place version

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

提交回复
热议问题