Python Forum
Sorting list of names by first two characters - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Sorting list of names by first two characters (/thread-10544.html)



Sorting list of names by first two characters - Otbredbaron - May-24-2018

I need to sort a list of n names where n is read by input, which ends when n is 0.
The thing is that the names must be sorted using only the first two characters and if two names have the same first two letters, they should stay in the same order as in the input.
This is the full text if it's needed and this is an example of the output.



This is the code that I wrote and even if it works I think that it could be better, especially the input part, so I'd like to know how to improve it:

#!/usr/bin/python3

while(True):
    n = int(input())
    if(n == 0):
        break
    a = []
    for i in range(n):
        s = input()
        a.append(s)
    a.sort(key=lambda x:x[:2], reverse = False)
    [print(i) for i in a]
    print("")



RE: Sorting list of names by first two characters - Larz60+ - May-24-2018

for sort use:
a.sort(key=lambda x:x[:2])



RE: Sorting list of names by first two characters - Otbredbaron - May-24-2018

Yeah, I forgot to temove the reverse flag because I was trying it a little bit. About the input I don't really like what I wrote but I couldn't find a better way