加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

排序 – Lua排序表按字母顺序排列,除了数字

发布时间:2020-12-15 00:16:40 所属栏目:大数据 来源:网络整理
导读:我想按字母顺序排序表.除了数字. 下面的代码显示了如何使用比较器函数对表进行排序: function( a,b ) return a.N b.N end 给我: obj = { [1] = { ["N"] = "Green 1"; }; [2] = { ["N"] = "Green 11"; }; [3] = { ["N"] = "Green 2"; }; [4] = { ["N"] = "R
我想按字母顺序排序表.除了数字.

下面的代码显示了如何使用比较器函数对表进行排序:

function( a,b ) return a.N < b.N end

给我:

obj = {
    [1] = {
        ["N"] = "Green 1";
    };
    [2] = {
        ["N"] = "Green 11";
    };
    [3] = {
        ["N"] = "Green 2";
    };
    [4] = {
        ["N"] = "Red 1";
    };
}

但是我希望它像这样排序:

obj = {
    [1] = {
        ["N"] = "Green 1";
    };
    [2] = {
        ["N"] = "Green 2";
    };
    [3] = {
        ["N"] = "Green 11";
    };
    [4] = {
        ["N"] = "Red 1";
    };
}

可能吗?

解决方法

本来打算发布这个,但是lhf发布的解决方案回答了你的问题.由于您仍然遇到问题,请尝试以下操作.
local function cmp(a,b)
   a = tostring(a.N)
   b = tostring(b.N)
   local patt = '^(.-)%s*(%d+)$'
   local _,_,col1,num1 = a:find(patt)
   local _,col2,num2 = b:find(patt)
   if (col1 and col2) and col1 == col2 then
      return tonumber(num1) < tonumber(num2)
   end
   return a < b
end

local obj = {
   { N = '1'           },{ N = 'Green1'      },-- works with optional space
   { N = 'Green'       },-- works when doesn't fit the format
   { N = 'Sky blue99'  },{ N = 'Green 11'    },{ N = 'Green 2'     },{ N = 'Red 02'      },-- works when has leading zeros
   { N = 'Red    01'   },-- works with padding spaces
   { N = 'Sky blue 42' },-- works with multi-word color names
   { N = 99            },-- works with numbers
}

table.sort(obj,cmp)
for i,v in ipairs(obj) do
   print(i,v.N)
end

打印:

1   1
2   99
3   Green
4   Green1
5   Green 2
6   Green 11
7   Red    01
8   Red 02
9   Sky blue 42
10  Sky blue99

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读