且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-02-03 22:29:57

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

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)