Is there a shorter way to make this function?

后端 未结 7 926
鱼传尺愫
鱼传尺愫 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-24 23:59

    This works,and it's simple and easy to understand.

    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
    

    Since you're new to Python,I tried to make it as simple as possible.

提交回复
热议问题