Search code examples
pythonstringslicealphabetical

How can I organize a list of strings alphabetically starting on a specific letter?


Example, if I have:

x = ['5 Gabriela', '4 Isabel', '1 Daniel', '1 Gabriel']

I want my output list to be organized by the names, not the numbers:

output_list = ['1 Daniel', '1 Gabriel', '5 Gabriela', '4 Isabel']

I tried doing some slicing but then my output list doesn't have the numbers:

names = []
for k in range (0, len(sum_sor)):
    start = x[k][2::]
    names.append(start)
    y = sorted(names)
print(y)

Output: y = ['Daniel', 'Gabriel', 'Gabriela', 'Ixchelle']


Solution

  • Use sorted with key being a lambda returning the name for each element of x

    sorted(x, key=lambda y: y.split()[1])