I have a list like L=['john fwtiou','nick dallas','kostas papadopoulos']
How do I sort it by the last names? the right should be first nick dallas
then john fwtiou
and then kostas papadopoulos
Simple solution using sorted()
.
>>> sorted(l, key=lambda name: name.split()[1])
['nick dallas', 'john fwtiou', 'kostas papadopoulos']
Try the following:
L = ['john fwtiou','nick dallas','kostas papadopoulos']
L_sorted = sorted(L, key=lambda name: name[name.find(' ')+1])
print(L_sorted)
Explanation: name[name.find(' ')+1]
finds the first letter after the space. The sorted
function then takes the list and sorts it with that as a custom key.
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.