I have a list of strings with alphanumeric values and i want to sort it using the in between value as parameter.
For example, i have the list below:
test = ["ykc 82 01" , "ao first qx" , "teste teste teste" , "a1 03 02" , "ga eai oie"]
I want to sort it but using the second value as parameter, for instance in this case the desired output should be that:
["ga eai oie" , "ao first qx" , "teste teste teste" , "a1 03 02" , "ykc 82 01"]
The first element is the string that has "eai" in the middle because it starts with the letter "e", the second element is the string that has "first" because starts with the letter "f", and so on, and the last elements are the ones who contains an numeric value, in any order.
i tried to sort with the sort function with an key, as this:
test.sort(key = lambda x: (x.split()[1]))
but it returns first the elements that contains numeric values and then the ones with digit values:
['a1 03 02', 'ykc 82 01', 'aa eai oie', 'eo first qx', 'teste teste teste']
CodePudding user response:
You need to pass in a slightly more complicated key
function:
test.sort(key=lambda x: chr(123) if x.split()[1].isnumeric() else x)
This outputs:
['ao first qx', 'ga eai oie', 'teste teste teste', 'ykc 82 01', 'a1 03 02']
Explanation:
The highest ASCII value of any alphabetic character is 122. Using chr(123)
gives us a character whose ASCII value is higher than all of the alphabetic characters, meaning that strings that are entirely numeric will be placed last.
CodePudding user response:
You could create a custom sorting function that returns a 2-tuple that will put alphabetic values first and numeric values last:
test = ["ykc 82 01" , "ao first qx" , "teste teste teste" , "a1 03 02" , "ga eai oie"]
def sort_func(value):
_, mid, _ = value.split()
return mid.isnumeric(), mid
print(sorted(test, key=sort_func))
Output:
['ga eai oie', 'ao first qx', 'teste teste teste', 'a1 03 02', 'ykc 82 01']