lua按某些键排序的方法
2024-10-21 09:56:46
function sort(list, ...)
local opts = {...};
local len = #opts;
return table.sort(list, function(a, b)
return comp(a, b, opts, 1, len);
end);
end
function comp(a, b, opts, i, len)
if (len >= i) then
local o = opts[i];
local k = o[1];
local asc = o[2] or true;
if (a[k] < b[k] == asc) then return true end;
if (a[k] == b[k]) then return comp(a, b, opts, i+1, len) end;
return false;
end
return false;
end
local l = {
{x=1,y=2,z=1},
{x=1,y=1,z=4},
{x=1,y=4,z=3},
{x=2,y=2,z=6},
{x=1,y=2,z=3},
{x=1,y=2,z=3},
{x=2,y=5,z=3},
{x=3,y=4,z=3},
{x=1,y=2,z=6},
{x=2,y=1,z=3},
{x=3,y=2,z=3},
}
sort(l, {"x",true},{"y",true},{"z",true});
for k,v in ipairs(l) do
print(k,v.x,v.y,v.z);
end
1 1 1 4
2 1 2 1
3 1 2 3
4 1 2 3
5 1 2 6
6 1 4 3
7 2 1 3
8 2 2 6
9 2 5 3
10 3 2 3
11 3 4 3
非递归版本
function sort(list, ...)
local opts = {...};
return table.sort(list, function(a, b)
for i, v in ipairs(opts) do
local k = v[1];
local asc = v[2] or true;
if (a[k] < b[k] == asc) then return true end;
if (a[k] ~= b[k]) then return false end;
end
return false;
end);
end
最新文章
- C#_基础:委托速讲
- What is “:-!!” in C code?
- nginx认证配置
- Learning jQuery, 4th Edition 勘误表
- ubuntu下firefox浏览器flash player插件的安装
- 使用BeanUtils工具类操作Java bean
- C++对象的自销毁
- 使用Httpwatch分析响应时间--转
- DOM元素拖拽效果
- mssql sqlserver isnull coalesce函数用法区别说明
- 用c# 开发html5的尝试,试用bridge.net
- day06 数字类型,字符串类型,列表类型
- ES6 迭代器和生成器
- $(";).each 和$.each
- 转【面向代码】学习 Deep Learning(二)Deep Belief Nets(DBNs)
- Java 8 实战
- SharePoint 站点导航Web部件
- python 标准库简介
- kotlin 遇到的问题
- [Winter Vacation] 守护,守望