[英]Sorting list of tuples containing numbers as strings
I'm new to programming and I'm not sure how to do this correctly. 我是编程新手,不知道如何正确执行此操作。 I'm trying to sort a list of tuples such as below by the second value and I need them to be sorted as if they were ints:
我正在尝试通过第二个值对诸如下面的元组列表进行排序,我需要对它们进行排序,就好像它们是整数一样:
[u'value3', '5,423']
[u'value', '1,389']
[u'value1', '3,385']
[u'anothervalue', '2,789']
[u'value2', '430']
Right now I have this: 现在我有这个:
sortedList= sorted(listToSort, key=lambda x: (x[1]))
as the result I get this: 结果我得到这个:
[u'value', '1,389']
[u'anothervalue', '2,789']
[u'value1', '3,385']
[u'value2', '430']
[u'value3', '5,423']
but I need it to be more like: 但我需要使其更像是:
[u'value3', '5,423']
[u'value1', '3,385']
[u'anothervalue', '2,789']
[u'value', '1,389']
[u'value2', '430']
or in ascending order, it doesn't matter. 或升序都没关系。 Any help is appreciated.
任何帮助表示赞赏。
You want the following: 您需要以下内容:
sortedList = sorted(listToSort, key=lambda x: int(x[1].replace(',', '')), reverse=True)
EDIT: original answer did descending, edited to be ascending 编辑:原始答案确实降序,编辑为升序
If your values are integers with comma as thousands delimiter, you should do: 如果您的值是带有逗号作为千位分隔符的整数,则应该执行以下操作:
sortedList = sorted(listToSort, key=lambda x: int(x[1].replace(",", "")))
If your values are float: 如果您的值是浮动的:
sortedList = sorted(listToSort, key=lambda x: float(x[1].replace(",", ".")))
Or you can set right locale to not use replace
: 或者,您可以设置正确的语言环境以不使用
replace
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.