我有一个和弦表与和弦名称和开始时间,有许多相同的名字在不同的开始时间。我需要随机选择一个匹配的chord_name
chord_name = "Cm7b5"
time = chords[chord_name].Start发布于 2019-11-03 08:37:38
因此,如果您需要从chord中随机选择一个chords[index].Name == chord_name,以便chords[index].Name == chord_name和您的索引依次为: 1、2、3、4、5(而不是例如: 52、96、121),那么您可以这样做:
chord_name = "Cm7b5"
index = math.random(#chords)
while chords[index].Name ~= chord_name do
index = math.random(#chords)
end
time = chords[index].Start(请注意,我没有选择一个和弦,而是选择了一个.Start时间,因为您的例子表明了这一点。)
但是,如果您有大量的数据,并且只有少数几个有.Name == chord_name,那么这很有可能(几乎)无限循环。
因此,确保对math.random()的单个调用将给我们一个明确的答案(索引)是一个很好的主意。
chord_name = "Cm7b5"
--we create an empty table
indexes = {}
--and store all indexes that fulfil the condition chords[index].Name == chord_name
for index, chord in pairs(chords) do
if chord.Name == chord_name then
table.insert(indexes, index)
end
end
--now we can randomly select from this table
index = indexes[math.random(#indexes)]
--which will always yield an index pointing to a chord with .Name == chord_name
time = chords[index].Start注意,使用pairs(chords)还可以从有孔的表(即{[1] = "a", [5] = "b", [16] = "c"})中选择和弦。
另一方面,如果您有大量(可能是数百万或100 K)的数据,后一种解决方案可能会有问题。迭代整个表并选择匹配的名称,并在此基础上创建一个新的表将非常耗时和内存。
https://stackoverflow.com/questions/58668752
复制相似问题