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

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

问题描述

我知道这听起来很琐碎,但是我没有意识到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.

我知道这可能是一个没有脑子的问题,但是Google和我的教科书没有提供比.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.

推荐答案

您实际上尚未将字符串转换为int.或更确切地说,您做了,但是随后您对结果什么也没做.您想要的是:

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天全站免登陆