Python Forum

Full Version: Sort a list that is embedded
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, i'm on a personnal project whose objective is to sort a list by name and not by first name.
However i have to keep the couple "name-firstname"

The user has to enter numbers in a list :

 [0, 1]  
These numbers correspond to people who are in this list :

 listepersonnes = [['RIETTE', 'JEAN', 'H', '28'], ['LAPORTE', 'LUCIE', 'H', '38']]
I would like the result to be :
['LAPORTE', 'LUCIE'], ['RIETTE', 'JEAN'] 
I have do it..
listepersonnes = [['RIETTE', 'JEAN', 'H', '28'], ['LAPORTE', 'LUCIE', 'H', '38']]
listetrie = []
for i in range (len(listepersonnes)):
    listetrie.append(listepersonnes[i][0])
    listetrie.sort()
    listetrie.append(listepersonnes[i][1])
 
print(listetrie)
I really don't know how to do it....
I have to do it with function too..

Thanks for help
I'm not quite clear on what you want the user's input numbers to do.  Could you provide some more detailed input and outputs?

Also:
>>> [person[:2] for person in sorted(listepersonnes)]
[['LAPORTE', 'LUCIE'], ['RIETTE', 'JEAN']]
>>>
Hello, sorry i'm french ahah :)
Your code is working correctly but he doesn't do the job i need ;)

 listpeople = [['RIETTE', 'JEAN', 'H', '28'], ['LAPORTE', 'LUCIE', 'H', '38']]
 
INPUT :
I ask to enter number or numbers for example it should do the job for: 0, 2
So I want the code to make sort from the 0 to the 2.

PROGRAM :

I have to make a function ( a definiton ) like this
def sortlist(INPUT):
 ????????????
 ????????????
OUTPUT :
It will sort the name of person like what you did past.

 [['LAPORTE', 'LUCIE'], ['RIETTE', 'JEAN']] 

Problem solved ;)with
 "return sorted([i[:2] for i in [maliste[j] for j in selection]])"
If sorting in-place is fine, then passing the key parameter to .sort is a faster way to do it than sorted().
>>> listpeople = [['RIETTE', 'JEAN', 'H', '28'], ['LAPORTE', 'LUCIE', 'H', '38']]
>>> sort_by = [0, 2]
>>> sort_start, sort_end = sort_by
>>> listpeople.sort(key=lambda person: person[sort_start:sort_end])
>>> listpeople
[['LAPORTE', 'LUCIE', 'H', '38'], ['RIETTE', 'JEAN', 'H', '28']]