Home > other >  How do you sort a python array into alphabetical order?
How do you sort a python array into alphabetical order?

Time:01-25

I was trying to do a task set by my friend (below) to help with my knowledge and I ran into a problem. I need to sort an array alphabetically, yet I cannot find anything anywhere to help with the problem. I have tried to use some sorting code that I have found, but that is for when the coder knows the inputs. However, because the user enters the inputs into an array I do not know how to proceed. The code and the task are below.

"Create a program that will let a teacher enter between 20-30 students( must be onput validation) once all 20-30 students entered make them in to an array with their last names deciding whether they are at the front or back of the register."

print ("Title: School Register")
print ("Date: 25/01/2022")

pupilNumber = int(input("How many pupils are in your class?"))
while pupilNumber < 20 or pupilNumber > 30:
      print ("That is not a valid number of pupils, please re-enter your number of pupils.")
      pupilNumber = int(input())

pupilName = [""]*pupilNumber 
for counter in range (0, pupilNumber):
      pupilName[counter] = str(input("Enter your pupils last names in alphabetical order."))
      
print ("The first person on the register is", pupilName[0])
print ("The last person on the register is", pupilName[counter])

CodePudding user response:

You can sort a list simply by calling its sort() method.

my_list = ["c", "a", "b"]
my_list.sort()
print(my_list)
# ["a", "b", "c"]

If you have any trouble due to mixing and matching capitalization, you can provide a sorting key.

my_list = ["c", "a", "B"]
my_list.sort()
print(my_list)
# ["B", "a", "c"]

my_list.sort(key=lambda entry: entry.lower())
print(my_list)
# ["a", "B", "c"]

These modify my_list in place. If you'd prefer to make a new list that is a sorted copy you can do new_list = sorted(my_list) or new_list = sorted(my_list, key=...)

CodePudding user response:

The answer it depends if you want to store the name and surname in two separated fields or not.

If you want to use a single field just for last name you can use the normal sort approach used for dictionaries, like mentioned from @buran.

sorted(pupilName)

If you are going to collect the name and surname you need to use a lambda function like explained here https://stackoverflow.com/a/20099713/18026877

sorted(pupilName, key=lambda x: x[1])

In this code I'm supposing that you store the name putting surname as second field.

  •  Tags:  
  • Related