sort a list in python

2

I want to make a program where I ask the user names and he keeps them and orders them alphabetically.

This is what I have now:

names = input("What are the names? ") 
print(names) 
sorted_names = sorted(names) 
print(sorted_names)

but when I run the program, this comes out

[' ', ' ', ' ', 'M', 'M', 'Z', 'a', 'a', 'c', 'c', 'i', 'l', 'o', 'o', 'p', 'r', 't', 't']

Sort each letter alphabetically.

How to make the names come out complete and ordered alphabetically?

    
asked by Microplo 17.10.2017 в 19:06
source

3 answers

5

The problem is that when you apply sorted to the string you convert the whole string into a list, that is, each character becomes an element of an ordered list.

You must create a list in which each name is an element and on it apply the ordering method. To do this, use the str.split method:

names = input("What are the names? ")
sorted_names = sorted(names.split())
print(sorted_names)

This is if you separate the names with spaces, otherwise pass to split the separator you want to use, for example to use a comma names.split(",") .

In case you want to order without having sensitivity to capitals (but without modifying the original string) you can use the key argument:

names = input("What are the names? ")
sorted_names = sorted(names.split(),  key=lambda x: x.lower())
print(sorted_names)
    
answered by 17.10.2017 / 19:15
source
2

If the user puts the names followed, separating by a comma, you can do so:

names = input("What are the names? ")
sorted_names = sorted(names.split(", "))
print(sorted_names)

If so, you can solve it that way, but rethink the question.

Greetings

    
answered by 17.10.2017 в 19:30
0

You can opt for a while loop that adds names to a list infinitely until you type a "keyword" in this case "Print".

When you enter "Print" the list is sorted by the .sort () command and printed.

nombre = input("Ingrese un nombre: ")
Lista = []
while nombre != "Imprimir":
    Lista.append(nombre)
    nombre = input("Ingrese otro nombre: ")

Lista.sort()
print(Lista)
    
answered by 18.10.2017 в 05:12