python,按每个元素的子字符串的键对列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/440541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:06:43  来源:igfitidea点击:

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

pythonlistsorting

提问by user33061

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)?

我目前正在尝试按进化的名称而不是数字的字母顺序对其进行排序。有什么方法可以做到这一点,而无需更改两件事出现在列表中的顺序(如在“智力 x 1”中)?

回答by S.Lott

You have to get the "key" from the string.

您必须从字符串中获取“密钥”。

def myKeyFunc( aString ):
    stuff, x, label = aString.partition(' x ')
    return label

aList.sort( key= myKeyFunc )

回答by dF.

How about:

怎么样:

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

回答by pboucher

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 sortmethod but you probably get the idea.

您可以编辑sort方法内部的解析,但您可能已经明白了。

Cheers, Patrick

干杯,帕特里克

回答by Justin Standard

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:

然后您使用该比较定义作为排序函数的输入:

myList.sort(myCompare)

回答by Teifion

As you are trying to sort what is essentially custom data, I'd go with a custom sort.

当您尝试对本质上是自定义数据的内容进行排序时,我会使用自定义排序。

Merge sort
Bubble sort
Quicksort

归并排序
冒泡排序
快速排序