将一个表中的无序键复制到另一个表中的有序值 [英] copying unordered keys from one table to ordered values in another

查看:83
本文介绍了将一个表中的无序键复制到另一个表中的有序值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,将字符串映射到像这样的数字:

I have a table mapping strings to numbers like this:

t['a']=10
t['b']=2
t['c']=4
t['d']=11

由此,我想创建一个类似数组的表,其值是第一个表中的键,按其在第一个表中的(降序)值排序,如下所示:

From this I want to create an array-like table whose values are the keys from the first table, ordered by their (descending) values in the first table, like this:

T[1] = 'd' -- 11
T[2] = 'a' -- 10
T[3] = 'c' -- 4
T[4] = 'b' -- 2

这在Lua中怎么做?

推荐答案

-- Your table
local t = { }
t["a"] = 10
t["b"] = 2
t["c"] = 4
t["d"] = 11

local T = { } -- Result goes here

-- Store both key and value as pairs
for k, v in pairs(t) do
  T[#T + 1] = { k = k, v = v }
end

-- Sort by value
table.sort(T, function(lhs, rhs) return lhs.v > rhs.v end)

-- Leave only keys, drop values
for i = 1, #T do
  T[i] = T[i].k
end

-- Print the result
for i = 1, #T do
  print("T["..i.."] = " .. ("%q"):format(T[i]))
end

它打印


T[1] = "d"
T[2] = "a"
T[3] = "c"
T[4] = "b"

这篇关于将一个表中的无序键复制到另一个表中的有序值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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