对一组值进行排序 [英] Sorting a set of values

查看:56
本文介绍了对一组值进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的价值观:

set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])设置(['4.918859000','0.060758000','4.917336999','0.003949999','0.013945000','10.281522000','82')]09

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

解决方案

来自评论:

<块引用>

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

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

<预><代码>>>>s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])>>>已排序['0.000000000'、'0.009518000'、'0.018384000'、'0.030810999'、'10.277200999'、'4.918560000']

<小时>

请注意,sorted 为您提供了一个 list,而不是一个 set.这是因为集合的全部意义,包括 数学几乎所有编程语言,*是它没有顺序:集合 {1,2}{2, 1} 是同一个集合.

<小时>

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

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

<预><代码>>>>排序(s,键=浮点数)['0.000000000'、'0.009518000'、'0.018384000'、'0.030810999'、'4.918560000'、'10.277200999']

<小时>

有关详细信息,请参阅官方文档中的Sorting HOWTO.

<小时>

* 例外情况见评论.

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.

解决方案

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.

这篇关于对一组值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆