Lua中如何对两个表使用同一顺序键进行并行排序?
- 内容介绍
- 文章标签
- 相关推荐
本文共计284个文字,预计阅读时间需要2分钟。
示例:使用table1和table2进行排序,不修改任一表,并返回排序后的第二个表。pythondef sort_tables(table1, table2): # 将table1中的元素按字典序排序,生成一个新的排序后的table1 sorted_table1=sorted(table1) # 返回排序后的第二个表table2 return sorted_table2
定义示例表table1=[2, 3, 1]table2=['a', 'b', 'c']
调用函数并输出结果sorted_table2=sort_tables(table1, table2)print(sorted_table2)
例:table1 = {2,3,1} table2 = {a,b,c}
至
table1 = {1,2,3} table2 = {c,a,b} 此函数不会修改任何一个表,并返回根据第一个表排序的第二个表.您可以在第一个表中传递键的比较,就像在table.sort中一样.
local sort_relative = function(ref, t, cmp) local n = #ref assert(#t == n) local r = {} for i=1,n do r[i] = i end if not cmp then cmp = function(a, b) return a < b end end table.sort(r, function(a, b) return cmp(ref[a], ref[b]) end) for i=1,n do r[i] = t[r[i]] end return r end
例如:
local table1 = {2, 3, 1} local table2 = {"a","b","c"} local sorted = sort_relative(table1, table2) print(table.unpack(sorted))
结果是:
c a b
本文共计284个文字,预计阅读时间需要2分钟。
示例:使用table1和table2进行排序,不修改任一表,并返回排序后的第二个表。pythondef sort_tables(table1, table2): # 将table1中的元素按字典序排序,生成一个新的排序后的table1 sorted_table1=sorted(table1) # 返回排序后的第二个表table2 return sorted_table2
定义示例表table1=[2, 3, 1]table2=['a', 'b', 'c']
调用函数并输出结果sorted_table2=sort_tables(table1, table2)print(sorted_table2)
例:table1 = {2,3,1} table2 = {a,b,c}
至
table1 = {1,2,3} table2 = {c,a,b} 此函数不会修改任何一个表,并返回根据第一个表排序的第二个表.您可以在第一个表中传递键的比较,就像在table.sort中一样.
local sort_relative = function(ref, t, cmp) local n = #ref assert(#t == n) local r = {} for i=1,n do r[i] = i end if not cmp then cmp = function(a, b) return a < b end end table.sort(r, function(a, b) return cmp(ref[a], ref[b]) end) for i=1,n do r[i] = t[r[i]] end return r end
例如:
local table1 = {2, 3, 1} local table2 = {"a","b","c"} local sorted = sort_relative(table1, table2) print(table.unpack(sorted))
结果是:
c a b

