Python 按字符串的一部分对字符串列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21431052/
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-08-18 22:50:09  来源:igfitidea点击:

Sort list of strings by a part of the string

pythonstringlistsorting

提问by erikfas

I have a list of strings which have the following format:

我有一个字符串列表,其格式如下:

['variable1 (name1)', 'variable2 (name2)', 'variable3 (name3)', ...]

... and I want to sort the list based on the (nameX)part, alphabetically. How would I go about doing this?

...我想根据(nameX)零件按字母顺序对列表进行排序。我该怎么做呢?

采纳答案by BartoszKP

To change sorting key, use the keyparameter:

要更改排序键,使用key参数

>>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
>>> s.sort(key = lambda x: x.split()[1])
>>> s
['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)']
>>> 

Works the same way with sorted:

以相同的方式工作sorted

>>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
>>> sorted(s)
['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
>>> sorted(s, key = lambda x: x.split()[1])
['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)']
>>> 

Note that, as described in the question, this will be an alphabetical sort, thus for 2-digit components it will not interpret them as numbers, e.g. "11" will come before "2".

请注意,如问题中所述,这将是字母排序,因此对于 2 位组件,它不会将它们解释为数字,例如“11”将在“2”之前。

回答by Ashwini Chaudhary

You can use regex for this:

您可以为此使用正则表达式:

>>> import re
>>> r = re.compile(r'\((name\d+)\)')
>>> lis = ['variable1 (name1)', 'variable3 (name3)', 'variable2 (name100)']
>>> sorted(lis, key=lambda x:r.search(x).group(1))
['variable1 (name1)', 'variable2 (name100)', 'variable3 (name3)']

Note that above code will return something like name100before name3, if that's not want you want then you need to do something like this:

请注意,上面的代码将返回类似name100before 的内容name3,如果这不是您想要的,那么您需要执行以下操作:

>>> r = re.compile(r'\(name(\d+)\)')
def key_func(m):
    return int(r.search(m).group(1))

>>> sorted(lis, key=key_func)
['variable1 (name1)', 'variable3 (name3)', 'variable2 (name100)']

回答by agastalver

Just use keyparameter of sortmethod.

只需使用方法的key参数sort

test.sort(key = lambda x: x.split("(")[1])

Good luck!

祝你好运!

Edit: testis the array.

编辑:test是数组。

回答by jermenkoo

The solution is:

解决办法是:

sorted(b, key = lambda x: x.split()[1])

Why? We want to sort the list (called b). As a key we will use (name X). Here we assume that it will be always preceded by space, therefore we split the item in the list to two and sort according to the second.

为什么?我们要对列表进行排序(称为 b)。我们将使用(名称 X)作为键。这里我们假设它总是前面有空格,因此我们将列表中的项目分成两个并根据第二个进行排序。