Python 如何按数字对字符串列表进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3426108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort a list of strings numerically?
提问by Brian
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.
我知道这听起来微不足道,但我没有意识到sort()Python的功能很奇怪。我有一个实际上是字符串形式的“数字”列表,所以我首先将它们转换为整数,然后尝试排序。
list1=["1","10","3","22","23","4","2","200"]
for item in list1:
item=int(item)
list1.sort()
print list1
Gives me:
给我:
['1', '10', '2', '200', '22', '23', '3', '4']
What I want is
我想要的是
['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.
我已经环顾了一些与排序数字集相关的算法,但我发现的所有算法都涉及对字母数字集进行排序。
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.
我知道这可能是一个简单的问题,但谷歌和我的教科书没有提供比该.sort()功能更多或更少有用的东西。
采纳答案by Seamus Campbell
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()
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 keyfunction. sorttakes 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:
如果由于某种原因您需要保留字符串而不是整数(通常是一个坏主意,但也许您需要保留前导零或其他内容),您可以使用键函数。sort接受一个命名参数,key,这是一个在比较之前在每个元素上调用的函数。比较键函数的返回值,而不是直接比较列表元素:
list1 = ["1","10","3","22","23","4","2","200"]
# call int(x) on each element before comparing it
list1.sort(key=int)
回答by kennytm
You could pass a function to the keyparameter to the .sortmethod. With this, the system will sort by key(x) instead of x.
你可以传递一个函数的key参数的.sort方法。有了这个,系统将按键(x)而不是 x 排序。
list1.sort(key=int)
BTW, to convert the list to integers permanently, use the mapfunction
顺便说一句,要将列表永久转换为整数,请使用该map函数
list1 = list(map(int, list1)) # you don't need to call list() in Python 2.x
or list comprehension
或列表理解
list1 = [int(x) for x in list1]
回答by Daniel Roseman
Python's sort isn't weird. It's just that this code:
Python 的排序并不奇怪。只是这段代码:
for item in list1:
item=int(item)
isn't doing what you think it is - itemis not replaced back into the list, it is simply thrown away.
没有做你认为的那样 -item没有被替换回列表,它只是被扔掉。
Anyway, the correct solution is to use key=intas others have shown you.
无论如何,正确的解决方案是key=int像其他人向您展示的那样使用。
回答by syam
回答by clint
The most recent solution is right. You are reading solutions as a string, in which case the order is 1, then 100, then 104 followed by 2 then 21, then 2001001010, 3 and so forth.
最近的解决方案是正确的。您正在阅读作为字符串的解决方案,在这种情况下,顺序是 1,然后是 100,然后是 104,然后是 2,然后是 21,然后是 2001001010、3 等等。
You have to CAST your input as an int instead:
您必须将您的输入转换为 int:
sorted strings:
排序字符串:
stringList = (1, 10, 2, 21, 3)
stringList = (1, 10, 2, 21, 3)
sorted ints:
排序整数:
intList = (1, 2, 3, 10, 21)
intList = (1, 2, 3, 10, 21)
To cast, just put the stringList inside int ( blahblah ).
要进行转换,只需将 stringList 放入 int ( blahblah ) 中。
Again:
再次:
stringList = (1, 10, 2, 21, 3)
newList = int (stringList)
print newList
=> returns (1, 2, 3, 10, 21)
回答by Kamal Reddy
scores = ['91','89','87','86','85']
scores.sort()
print (scores)
This worked for me using python version 3, though it didn't in version 2.
这对我使用 python 版本 3 有效,尽管它在版本 2 中没有。
回答by Julian
You can also use:
您还可以使用:
import re
def sort_human(l):
convert = lambda text: float(text) if text.isdigit() else text
alphanum = lambda key: [convert(c) for c in re.split('([-+]?[0-9]*\.?[0-9]*)', key)]
l.sort(key=alphanum)
return l
This is very similar to other stuff that you can find on the internet but also works for alphanumericals like [abc0.1, abc0.2, ...].
这与您可以在互联网上找到的其他内容非常相似,但也适用于[abc0.1, abc0.2, ...].
回答by Marx Wolf
Seamus Campbell's answer doesnot work on python2.x.list1 = sorted(list1, key=lambda e: int(e))using lambdafunction works well.
Seamus Campbell的回答在 python2.x 上不起作用。list1 = sorted(list1, key=lambda e: int(e))使用lambda功能效果很好。
回答by rfaenger
I approached the same problem yesterday and found a module called natsort, which solves your problem. Use:
我昨天解决了同样的问题,发现了一个名为natsort的模块,它解决了你的问题。用:
from natsort import natsorted
# Example list of strings
a = ['1', '10', '2', '3', '11']
[In] sorted(a)
[Out] ['1', '10', '11', '2', '3']
[In] natsorted(a)
[Out] ['1', '2', '3', '10', '11']
It also works for dictionaries as an equivalent of sorted.
它也适用于字典,相当于sorted.
回答by sayalok
Simple way to sort a numerical list
对数字列表进行排序的简单方法
numlists = ["5","50","7","51","87","97","53"]
results = list(map(int, numlists))
results.sort(reverse=False)
print(results)

