简体   繁体   English

如何使用姓氏和名字对列表进行排序

[英]How do i sort a list with first and last name by the last names

I have a list like L=['john fwtiou','nick dallas','kostas papadopoulos'] How do I sort it by the last names? 我有一个像L=['john fwtiou','nick dallas','kostas papadopoulos']如何按姓氏对它进行排序? the right should be first nick dallas then john fwtiou and then kostas papadopoulos 右边应该是nick dallas然后是john fwtiou ,然后是kostas papadopoulos

Simple solution using sorted() . 使用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. 说明: name[name.find(' ')+1]查找空格后的第一个字母。 The sorted function then takes the list and sorts it with that as a custom key. 然后,已sorted函数获取列表,并将其作为自定义键对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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