Home > front end >  how can I print names in alphabetical order?
how can I print names in alphabetical order?

Time:10-06

In this program, how can I print names in each gender in alphabetical order?

n = int(input())
names = []
f = []
m = []

for i in list(range(n)):
    temp = input()
    tmplst = temp.split(".")
    str = f"{tmplst[1]} = {tmplst}"
    str = str.replace("[","(")
    str = str.replace("]",")")
    print(str)
    exec(str)
    if tmplst[0] == "m":
        exec(f"m.append({tmplst[1]})")
    elif tmplst[0] == "f":
        exec(f"f.append({tmplst[1]})")
    #exec(f"print({tmplst[1]})")

for i in list(range(len(m))):
    print(f[i][0],f[i][1].capitalize(),f[i][2])

for i in list(range(len(m))):
    print(m[i][0],m[i][1].capitalize(),m[i][2])

CodePudding user response:

In general you have following options: sorted() or list.sort() either using lambda or using itemgetter() which is slightly faster.

Using sorted() with lambda:

your_list_sorted = sorted(your_list_unsorted, key = lambda x: x[<1st index>], x[<2nd key>], x[...])

Using sorted() with itemgetter():

import operator
your_list_sorted = sorted(your_list_unsorted, key = operator.itemgetter(<1st index>, <2nd index>, ...))

Using list.sort() with lambda:

your_list.sort(key=lambda x: x[<1st index>], x[<2nd key>], x[...])

Using list.sort() with itemgetter():

import operator
your_list.sort(key=operator.itemgetter(<1st index>, <2nd index>, ...))

Example with

- Single sorting:

# sorted() - lambda:
your_list_sorted = sorted(your_list_unsorted, key = lambda x: x[1])

# sorted() - itemgetter():
import operator
your_list_sorted = sorted(your_list_unsorted, key = operator.itemgetter(1))

# list.sort() - lambda:
your_list.sort(key=lambda x: x[1])

# list.sort() - itemgetter():
import operator
your_list.sort(key=operator.itemgetter(1))

- Multiple sorting:

# sorted() - lambda:
your_list_sorted = sorted(your_list_unsorted, key = lambda x: (x[0], x[1]))

# sorted() - itemgetter():
import operator
your_list_sorted = sorted(your_list_unsorted, key = operator.itemgetter(1, 2))

# list.sort() - lambda:
your_list.sort(key=lambda x: x[0], x[1])

# list.sort() - itemgetter():
import operator
your_list.sort(key = operator.itemgetter(0, 1))

CodePudding user response:

data = ['Elle', 'Miles', 'Kratos', 'Joel', 'Peter', 'Nathan']

print(sorted(data))

CodePudding user response:

Using sorted() should solve the problem

CodePudding user response:

You can use the max() built-in function, or also the sorted() one.

Sorted

>>> sorted(["La", "Le", "Hen", "Han"])
['Han', 'Hen', 'La', 'Le']
  • Related