Reputation: 31
I have a list of list of strings. I want to sort the list based on characters after the first space(alphanumeric Sort). if the characters after the first space is same,then sort by the characters before the first space
L2 = ["ea first qpx", "India Kashmir Equator Khidderpore", "India Kashmir Alipore" , "az0 first qpx", "India Ambati Chembur Mahavir"]
Upvotes: 3
Views: 1147
Reputation: 21
Sort the inner list making use of Lambda expression in sort()
L2.sort(key = lambda x : (x.split(" ")[1].lower(), x.split(" ")[0].lower()))
This will split the inner list by spaces and sort it on the basis of first character set after space. If first characters are same then characters present at zeroth index will be considered.
lower() is used to make sorting case insensitive. If not used then strings with uppercase characters will have higher precedence over the lowercase characters.
Examples:
>> L2 = ["x c t", "a a g", "c a g"]
>> L2.sort(key = lambda x : (x.split(" ")[1].lower(), x.split(" ")[0].lower()))
>> L2
['a a g', 'c a g', 'x c t']
L2 = ["ea first qpx", "India Kashmir Equator Khidderpore", "India Kashmir Alipore" , "az0 first qpx", "India Ambati Chembur Mahavir"]
>> L2.sort(key = lambda x : (x.split(" ")[1].lower(), x.split(" ")[0].lower()))
>> L2
['India Ambati Chembur Mahavir', 'az0 first qpx', 'az0 first qpx', 'India Kashmir Equator Khidderpore', 'India Kashmir Alipore']```
Upvotes: 2
Reputation: 57
This also works:
def sortListAfterSpaceSplit(myList):
newList = []
for val in myList:
# split the string
s = val.split(' ', 1)
newList.append(s[1])
newList.sort()
return newList
Upvotes: 0
Reputation: 57
This works and returns
sorted new list
['Ambati Chembur Mahavir', 'Kashmir Alipore', 'Kashmir Equator Khidderpore', 'first qpx', 'first qpx']
Here is the code:
L2 = ["ea first qpx", "India Kashmir Equator Khidderpore", "India Kashmir Alipore" , "az0 first qpx", "India Ambati Chembur Mahavir"]
def sortListAfterSpaceClean(myList):
newList = []
for i, val in enumerate(myList):
# create a list of the characters
z = list(val)
for j, jVal in enumerate(z):
if jVal == " ":
# we want the rest of the string
lenOfString = len(val) - j - 1
restOfString = val[-lenOfString:]
newList.append(restOfString)
break
print('the old list:')
print(myList)
print('the new list:')
print(newList)
print('sorted new list')
newList.sort()
print(newList)
return newList
sortListAfterSpaceClean(L2)
Feel free to edit & comment accordingly.
Upvotes: 0