Python Forum
Sorting list of names by first two characters
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting list of names by first two characters
#1
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("")
Reply
#2
for sort use:
a.sort(key=lambda x:x[:2])
Reply
#3
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  sorting a list using unicodes acending order, no loops, no sort(), using recursion lrn2codee 14 6,248 Jun-23-2021, 07:33 PM
Last Post: deanhystad
  Sorting list - Homework assigment ranbarr 1 2,200 May-16-2021, 04:45 PM
Last Post: Yoriz
  Input validation for nested dict and sorting list of tuples ranbarr 3 3,841 May-14-2021, 07:14 AM
Last Post: perfringo
  Change each character of list into an different characters Angry_bird89 1 2,022 Jun-19-2020, 08:29 AM
Last Post: Angry_bird89
  Question about Sorting a List with Negative and Positive Numbers Than999 2 12,592 Nov-14-2019, 02:44 AM
Last Post: jefsummers
  CODE for Bubble sorting an unsorted list of 5 numbers. SIJAN 1 2,255 Dec-19-2018, 06:22 PM
Last Post: ichabod801
  sorting a deck of cards (objects in a list) itmustbebunnies 1 7,145 Dec-05-2018, 02:44 AM
Last Post: ichabod801
  Help with list sorting gonzo620 1 3,070 Oct-16-2018, 02:58 PM
Last Post: j.crater
  Advanced sorting of a built-in list Whisper40 6 4,050 Jan-11-2018, 07:27 PM
Last Post: Whisper40
  Sorting Santa's List of Children sirox84 4 5,094 Feb-20-2017, 06:10 PM
Last Post: sirox84

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020