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']
.
a=['bbb', 'ccc', 'axx', 'xzz', 'xaa']
a1=['mix', 'xyz','apple', 'xanadu', 'aardvark','xz']
xlist=[]
def sort(s):
for i in s:
if i[0]=='x':
xlist.append(i)
s.remove(i)
print sorted(xlist)+sorted(s)
del xlist[:]
sort(a)
sort(a1)
This code works as long as two list elements which start with x dont come together. i.e I get proper output for list a1 but not for a can you help me understand why!
obtained output.
['xzz', 'axx', 'bbb', 'ccc', 'xaa']
['xanadu', 'xyz', 'xz', 'aardvark', 'apple', 'mix']
In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .
The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.
Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.
You can use sorted
or list.sort
with two keys:
l = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark']
sorted(l, key=lambda x: (not x.startswith('x'), x))
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
where not x.startswith('x')
returns bool
, which gets sorted in False
first. Thus, not x.startswith('x')
grabs the strs that start with 'x' and bring them to the front.
You are not suppose to remove from the list while iterating over it, try it with a deep copy:
a=['bbb', 'ccc', 'axx', 'xzz', 'xaa']
a1=['mix', 'xyz','apple', 'xanadu', 'aardvark','xz']
xlist=[]
def sort(s):
for elem in s[:]:
if elem.startswith('x'):
xlist.append(elem)
s.remove(elem)
print(sorted(xlist)+sorted(s))
del xlist[:]
sort(a)
sort(a1)
OUTPUT:
['xaa', 'xzz', 'axx', 'bbb', 'ccc']
['xanadu', 'xyz', 'xz', 'aardvark', 'apple', 'mix']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With