gpt4 book ai didi

sorting - 关联数组排序值

转载 作者:行者123 更新时间:2023-12-01 12:37:15 25 4
gpt4 key购买 nike

我有以下代码应该返回一个基于其“pos”值排序的数组。

local tables = {}

table.insert(tables,{ ['pos']=2, ['name'] = 'C' })
table.insert(tables, {['pos']=1, ['name'] = 'A' })
table.insert(tables,{ ['pos']=30, ['name'] = 'D'} )


function comp(w1,w2)
if tonumber(w1['pos']) > tonumber(w2['pos']) then
return true
end
end

table.sort(tables, comp)

for key,val in pairs(tables) do
print(val['name'])
end

结果是:

DC一个

预期(按“位置”字母顺序排序):

一个,C,

怎么了?

最佳答案

来自 PILtable.sort(table [, comp]) 的文档:

[comp] This order function receives two arguments and must return true if the first argument should come first in the sorted array

所以把函数改成:

function comp(w1,w2)
return w1['pos'] < w2['pos']
end

注意 tonumber 和 if 在这里都是不必要的。

正如@lhf 指出的那样,这还可以变得更简单:

table.sort(tables, function(w1, w2) return w1.pos < w2.pos end)

关于sorting - 关联数组排序值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28589792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com