简体   繁体   English

将字符串转换为整数,然后在带有字符串的列表中对其进行排序

[英]Converting strings to integers then ordering them in an list with strings

I have the following list and I need to order them from biggest to smallest names and numbers. 我有以下列表,我需要按从大到小的顺序对它们进行排序。

['joe:  5', 'ed:  9', 'joe:  7', 'ed:  8']

I'm having the following problems: 我遇到以下问题:

  1. Converting the numbers from strings to integers to order it. 将数字从字符串转换为整数以对其进行排序。
  2. Ordering them with the correct string. 用正确的字符串排序。

So my end result should be this: 所以我的最终结果应该是这样的:

['ed:  9', 'ed:  8', 'joe:  7', 'joe:  5']
>>> lis=['joe:  5', 'ed:  9', 'joe:  7', 'ed:  8']

>>> sorted(lis,key=lambda x:int(x.split()[-1]),reverse=True)
>>> ['ed:  9', 'ed:  8', 'joe:  7', 'joe:  5']

you can fetch the integers in each list item using str.split (as shown below), and that integer is then used to sort the list: 您可以使用str.split提取每个列表项中的整数(如下所示),然后使用该整数对列表进行排序:

>>> int(lis[0].split(":")[1])
>>> 5

#or  

>>> int(lis[0].split()[1]) 
>>> 5

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

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