简体   繁体   中英

Rearranging a sublist within a list

I am having a hard time rearanging a list of tuples of names, first and last. I want to sort the list by last name and if there are identical last names then the sublist of those names should be arranged by first name. The first part was pretty easy with sorted and key=get_key1 but I am having diffuculties to complete the second part of the problem.

A list like this:

[('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

should come out like:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

Best I got is:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Haim', 'Cohen'), ('Gil', 'Cohen'), ('Tom', 'Haim'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Ben', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

Thank you

If you return a tuple as a key it will first sort by the first element and then by the second. Since you want to sort by first last name then first name your key should return (last name, first name) .

l = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

def get_key1(x):
    return (x[1], x[0])

print(sorted(l, key=get_key1))

You can sort the list of the fly using the sort() method of list :

inlist = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]
inlist.sort(key = lambda i: (i[1],i[0]))
print(inlist)

Output:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

An alternative to lambda , suggested by @cezar would be itemgetter from the operator module:

from operator import itemgetter

inlist = [('Tom','Haim'),('Eli','Levi'),('Eli','Cohen'),('Moshe','Levi'),('Haim','Cohen'),('Dina','Ram'),('Tova','Ben'),('Ben','Levi'),('Gil','Cohen'),('Eli','Ram')]

inlist.sort(key = itemgetter(1,0))
print(inlist)

Output:

[('Tova', 'Ben'), ('Eli', 'Cohen'), ('Gil', 'Cohen'), ('Haim', 'Cohen'), ('Tom', 'Haim'), ('Ben', 'Levi'), ('Eli', 'Levi'), ('Moshe', 'Levi'), ('Dina', 'Ram'), ('Eli', 'Ram')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM