Python 对一组值进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17457793/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:16:15  来源:igfitidea点击:

Sorting a set of values

python

提问by Justin Carrey

I have values like this:

我有这样的价值观:

set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
set(['4.918859000', '0.060758000', '4.917336999', '0.003949999', '0.013945000', '10.281522000', '0.025082999'])  

I want to sort the values in each setin increasing order. I don't want to sort between the sets, but the values in each set.

我想按升序对每个值进行排序set。我不想在集合之间排序,而是每个集合中的值。

采纳答案by abarnert

From a comment:

来自评论:

I want to sort each set.

我想对每个集合进行排序。

That's easy. For any set s(or anything else iterable), sorted(s)returns a list of the elements of sin sorted order:

这很容易。对于任何集合s(或任何其他可迭代对象),sorted(s)返回s按排序顺序的元素列表:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']


Note that sortedis giving you a list, not a set. That's because the whole point of a set, both in mathematicsand in almost every programming language,* is that it's not ordered: the sets {1, 2}and {2, 1}are the same set.

请注意,这sorted是给您一个list,而不是一个set。那是因为集合的全部意义,无论是在数学中还是在几乎所有编程语言中,* 都在于它没有顺序:集合{1, 2}{2, 1}是同一个集合。



You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

您可能真的不想将这些元素作为字符串排序,而是作为数字排序(因此 4.918560000 将在 10.277200999 之前而不是之后)。

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a keyfunction:

最好的解决方案是最有可能将数字存储为数字而不是字符串。但如果没有,你只需要使用一个key函数:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']


For more information, see the Sorting HOWTOin the official docs.

有关更多信息,请参阅官方文档中的Sorting HOWTO



* See the comments for exceptions.

* 有关例外情况,请参阅注释。