python,按键对列表进行排序,键是每个元素的子字符串 [英] python, sorting a list by a key that's a substring of each element
本文介绍了python,按键对列表进行排序,键是每个元素的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
程序的一部分将构建此列表,
Part of a programme builds this list,
[u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale']
我目前正在尝试按演变名称而不是数字按字母顺序对其进行排序.我有什么办法可以做到而又不改变这两个东西在列表中的显示顺序(如'intellect x 1)?
I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?
推荐答案
您必须从字符串中获取键".
You have to get the "key" from the string.
def myKeyFunc( aString ):
stuff, x, label = aString.partition(' x ')
return label
aList.sort( key= myKeyFunc )
这篇关于python,按键对列表进行排序,键是每个元素的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文