我如何在 ruby 中按字母数字对数组数据进行排序?
假设我的数组是 a = [test_0_1, test_0_2, test_0_3, test_0_4, test_0_5, test_0_6, test_0_7, test_0_8, test_0_9, test_1_0, test_1_1, test_1_2, test_1_3, test_1_4, test_1_5, test_1_6, test_1_7, test_1_98, test_1 , test_1_10, test_1_11, test_1_12, test_1_13, test_1_14, ......test_1_121......]
我希望我的输出是:
.
.
.
test_1_121
.
.
.
test_1_14
test_1_13
test_1_12
test_1_11
test_1_10
test_1_9
test_1_8
test_1_7
test_1_6
test_1_5
test_1_4
test_1_3
test_1_2
test_1_1
test_0_10
test_0_9
test_0_8
test_0_7
test_0_6
test_0_5
test_0_4
test_0_3
test_0_2
test_0_1
最佳答案
一种通用算法,用于对在任意位置包含非填充序列号的字符串进行排序。
padding = 4
list.sort{|a,b|
a,b = [a,b].map{|s| s.gsub(/\d+/){|m| "0"*(padding - m.size) + m } }
a<=>b
}
其中填充是您希望数字在比较过程中具有的字段长度。如果在字符串中找到的任何数字少于“填充”位数,则在比较之前将用零填充,这会产生预期排序顺序。
要生成 user682932 要求的结果,只需在排序 block 后添加 .reverse
,这会将自然排序(升序)翻转为降序。
通过对字符串进行预循环,您当然可以动态地找到字符串列表中的最大位数,您可以使用它来代替硬编码一些任意填充长度,但这需要更多的处理(速度较慢) 和更多的代码。例如
padding = list.reduce(0){|max,s|
x = s.scan(/\d+/).map{|m|m.size}.max
(x||0) > max ? x : max
}
关于ruby - 如何在 ruby 中对字母数字数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5480703/