如何对字符串列表进行数字排序?

编程入门 行业动态 更新时间:2024-10-16 22:18:07
本文介绍了如何对字符串列表进行数字排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

如何对字符串列表进行数字排序?

本文发布于:2023-06-08 21:31:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589412.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!