简体   繁体   English

Python-如何对字符串列表进行排序

[英]Python - How to sort a list of strings

I would like to sort this list: 我想对这个列表进行排序:

my_list = ["32,6,bob", "5,21,fred", "100,9,sid"]

by the second number in each string in descending order. 按每个字符串中第二个数字的降序排列。 Like this: 像这样:

["5,21,fred", "100,9,sid", "32,6,bob"]

I know I can change it to a list of lists and sort it like this: 我知道我可以将其更改为列表列表并按以下方式对其进行排序:

my_list = [["32", "6", "bob"], ["5", "21", "fred"], ["100", "9", "sid"]]
my_list.sort(reverse=True, key=lambda x: x[1])

But it's annoying to have to change it to lists and then string it afterwards (It's to be written to a file), so I was wondering if there's a way to sort it as strings. 但是必须将其更改为列表,然后再将其字符串化(将其写入文件),这很烦人,所以我想知道是否存在一种将其排序为字符串的方法。

In [1]: sorted(["32,6,bob", "5,21,fred", "100,9,sid"],
   ...:        key=lambda s: int(s.split(',')[1]),
   ...:        reverse=True)
Out[1]: ['5,21,fred', '100,9,sid', '32,6,bob']

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

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