[英]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: 我遇到以下问题:
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.