我该如何排序这个列表?
我有一个列表,里面又包含了很多小列表。
List<List<T>> li = {
{a1,a2,a3 ... aN},
{b1,b2,b3 ... bN},
...
};
double foo(List<T> list)
{
// do something
// e.g {1,2,3}
// it = 1 + 2 + 3
return it;
}
现在我想把这个列表排序,排序的规则是:如果某个小列表里的 foo(x)
值越大,它在排序后的列表中就应该排得越前。
用C#/Python/其他语言,怎么做这个排序最好呢?
11 个回答
5
这就是用Python的方法:只需要把函数作为 key
参数传给 sorted()
或 .sort()
就可以了:
>>> mylist = [123, 765, 4, 13]
>>> def mod5(x):
... return x%5
...
>>> sorted(mylist, key = mod5)
[765, 123, 13, 4]
>>> sorted(mylist, key = mod5, reverse = True)
[4, 123, 13, 765]
10
Haskell的解决方案特别优雅,使用了来自Data.Function的on
组合器。
import Data.Function (on)
import Data.List (sortBy)
lists = [ [ 5, 6, 8 ]
, [ 1, 2, 3 ]
]
main = do
print $ sortBy (compare `on` foo) lists
where
foo = sum
输出结果:
[[1,2,3],[5,6,8]]
还有来自Data.Ord的comparing
,让我们可以这样写:
main = do
print $ sortBy (comparing foo) lists
where
foo = sum
comparing
的定义非常简单:
comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering
comparing p x y = compare (p x) (p y)
但我们也可以用on
来定义它:
comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering
comparing f = compare `on` f
或者完全不使用点的方式来写:
comparing :: (Ord b) => (a -> b) -> a -> a -> Ordering
comparing = (compare `on`)
Haskell处理函数的能力就像Perl处理字符串一样强大。
10
用一点点LINQ:
var q = from el in li
orderby foo(el)
select el;
li = q.ToList();