按字符串的一部分对字符串列表进行排序 [英] Sort list of strings by a part of the string
本文介绍了按字符串的一部分对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有以下格式的字符串列表:
I have a list of strings which have the following format:
['variable1 (name1)', 'variable2 (name2)', 'variable3 (name3)', ...]
...,我想根据(nameX)
部分按字母顺序对列表进行排序.我将如何去做?
... and I want to sort the list based on the (nameX)
part, alphabetically. How would I go about doing this?
推荐答案
To change sorting key, use the key
parameter:
>>>s = ['variable1 (name3)', 'variable2 (name2)', 'variable3 (name1)']
>>> s.sort(key = lambda x: x.split()[1])
>>> s
['variable3 (name1)', 'variable2 (name2)', 'variable1 (name3)']
>>>
与 sorted
相同的工作方式:
Works the same way with 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)']
>>>
请注意,如问题所述,这将是字母顺序的排序,因此对于2位数字的组件,它不会将它们解释为数字,例如"11"将出现在"2"之前.
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".
这篇关于按字符串的一部分对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文