Is There A Shorter Way To Make This Function?
Solution 1:
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:
deffront_x(words):
returnsorted(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.
Solution 2:
Use list comprehensions
list = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
list.sort()
listA = [item foritemin list if item[0] == 'x']
listB = [item foritemin list if item[0] != 'x']
listC = listA + listB
Solution 3:
This works,and it's simple and easy to understand.
deffront_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.
Solution 4:
The error for your return is because sort does not return a value, it merely modifies the list.
This seems a fairly fast way to do this, it runs in linear time, you won't get much faster than that. That being said, you could do inline code to shorten it, but it's not always more readable that way.
Solution 5:
>>> l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
>>> sorted ([x for x in l if x.startswith('x')]) + sorted([x for x in l ifnot x.startswith('x')])
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
Post a Comment for "Is There A Shorter Way To Make This Function?"