简体   繁体   English

python,通过一个键来排序列表,该键是每个元素的子串

[英]python, sorting a list by a key that's a substring of each element

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']

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)? 有没有什么方法可以做到这一点,而不只是改变列表中出现的两个东西的顺序(如'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 )

怎么样:

lst.sort(key=lamdba s: s.split(' x ')[1])

Not knowing if your items are standardized at 1 digit, 1 space, 1 'x', 1 space, multiple words I wrote this up: 不知道你的物品是否标准化为1位数,1个空格,1个'x',1个空格,多个单词我写了这个:

mylist = [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']
def sort(a, b):
  return cmp(" ".join(a.split()[2:]), " ".join(b.split()[2:]))

mylist.sort(sort)

You can edit the parsing inside the sort method but you probably get the idea. 您可以在sort方法中编辑解析,但您可能会得到这个想法。

Cheers, Patrick 干杯,帕特里克

To do so, you need to implement a custom compare: 为此,您需要实现自定义比较:

def myCompare(x, y):
   x_name = " ".join(x.split()[2:])
   y_name = " ".join(y.split()[2:])
   return cmp(x_name, y_name)

Then you use that compare definition as the input to your sort function: 然后使用该比较定义作为sort函数的输入:

myList.sort(myCompare)

As you are trying to sort what is essentially custom data, I'd go with a custom sort. 当您尝试对基本上是自定义数据进行排序时,我会使用自定义排序。

Merge sort 合并排序
Bubble sort 冒泡排序
Quicksort 快速排序

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

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