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

编程入门 行业动态 更新时间:2024-10-27 06:21:19
本文介绍了按字符串的一部分对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个具有以下格式的字符串列表:

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?

推荐答案

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

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".

更多推荐

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

本文发布于:2023-10-18 03:26:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502942.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!