问题:对一组值进行排序[关闭]

我有这样的价值观:

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'])  

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

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 set in increasing order. I don’t want to sort between the sets, but the values in each set.


回答 0

来自评论:

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

这很简单。对于任何集合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']

请注意,这sorted是给您一个list,而不是一个set。这是因为在数学几乎每种编程语言中,集合的全部要点*都是无序的:集合{1, 2}{2, 1}是同一集合。


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

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

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

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


*请参阅注释以了解exceptions情况。

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 s in sorted order:

>>> 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 sorted is giving you a list, not a set. That’s because the whole point of a set, both in mathematics and in almost every programming language,* is that it’s not ordered: the sets {1, 2} and {2, 1} are the same set.


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).

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 key function:

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

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。