如何按数字对字符串列表进行排序? [英] How to sort a list of strings numerically?

查看:49
本文介绍了如何按数字对字符串列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这听起来微不足道,但我没有意识到 Python 的 sort() 函数很奇怪.我有一个实际上是字符串形式的数字"列表,所以我首先将它们转换为整数,然后尝试排序.

I know that this sounds trivial but I did not realize that the sort() function of Python was weird. I have a list of "numbers" that are actually in string form, so I first convert them to ints, then attempt a sort.

list1=["1","10","3","22","23","4","2","200"]
for item in list1:
    item=int(item)

list1.sort()
print list1

给我:

['1', '10', '2', '200', '22', '23', '3', '4']

我想要的是

['1','2','3','4','10','22','23','200']

我已经环顾了一些与排序数字集相关的算法,但我发现的所有算法都涉及对字母数字集进行排序.

I've looked around for some of the algorithms associated with sorting numeric sets, but the ones I found all involve sorting alphanumeric sets.

我知道这可能是一个简单的问题,但谷歌和我的教科书没有提供比 .sort() 函数更多或更少有用的东西.

I know this is probably a no brainer problem but google and my textbook don't offer anything more or less useful than the .sort() function.

推荐答案

您实际上还没有将字符串转换为整数.或者更确切地说,你做了,但你没有对结果做任何事情.你想要的是:

You haven't actually converted your strings to ints. Or rather, you did, but then you didn't do anything with the results. What you want is:

list1 = ["1","10","3","22","23","4","2","200"]
list1 = [int(x) for x in list1]
list1.sort()

如果出于某种原因您需要保留字符串而不是整数(通常是个坏主意,但也许您需要保留前导零或其他内容),您可以使用 key 函数.sort 接受一个命名参数,key,这是一个在比较每个元素之前调用的函数.比较关键函数的返回值,而不是直接比较列表元素:

If for some reason you need to keep strings instead of ints (usually a bad idea, but maybe you need to preserve leading zeros or something), you can use a key function. sort takes a named parameter, key, which is a function that is called on each element before it is compared. The key function's return values are compared instead of comparing the list elements directly:

list1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)

这篇关于如何按数字对字符串列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆