Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to make this function?

Tags:

python

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', 'xanadu', 'aardvark'] yields ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] Hint: this can be done by making 2 lists and sorting each of them before combining them.

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)

I'm new to python and programming in general but I feel there is a more compact way to write this code or is there a more 'pythonic' way?

also I tried to return the line:

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

but this erred out. Why did that happen?

like image 204
user2093601 Avatar asked Nov 22 '25 11:11

user2093601


2 Answers

You could sort words with one call to sorted using the key parameter to "teach" sorted how you wish the items in words to be ordered:

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

The key function is called once for every item in words and returns a proxy value by which the items in words is to be sorted. tuples such as the one returned by the lambda function above, are sorted in lexicographic order (according to the first item in the tuple, and according to the second to break ties).

This technique as well as others is explained in the excellent Sorting Howto.


For example,

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

Note that if words contains an empty string, word[0] will raise an IndexError. In contrast ''.startswith('x') returns False. So use word.startswith('x') if you wish front_x to handle empty strings, and use word[0] == 'x' if you wish to raise an exception.

like image 100
unutbu Avatar answered Nov 25 '25 02:11

unutbu


Use list comprehensions

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
like image 21
tom Avatar answered Nov 25 '25 00:11

tom