【问题标题】:How to sort an array of ints and strings? [duplicate]如何对整数和字符串数组进行排序? [复制]
【发布时间】:2016-04-21 04:48:35
【问题描述】:

我正在尝试对包含整数和字符串的数组进行排序。举个例子:

a = ["a", "b", 5, "c", 4, "d", "a1", "a12", 3, 13, 2, "13a", "12a"]

我试过了:

a.sort do |x, y|
  if x.class == y.class
    x <=> y
  else
    x.class.to_s <=> y.class.to_s
  end
end

返回:

[2, 3, 4, 5, 13, "12a", "13a", "a", "a1", "a12", "b", "c", "d"]

我想要的结果是:

[2, 3, 4, 5, "12a", 13, "13a", "a", "a1", "a12", "b", "c", "d"]

【问题讨论】:

  • 字符串中可以有多个数字,例如"a1b2c3"?
  • 什么是正确的? ["a1", "a12", "a2"]["a1", "a2", "a12"]?
  • @Stefan 字符串中可能有多个数字。后者["a1", "a2", "a12"]
  • @ChristianFazzini,即使在字符串中有多个数字的情况下,更新版本也可以工作。看看吧。

标签: arrays ruby sorting natural-sort


【解决方案1】:
a.sort_by { |x| [(x.to_s.match(/^\d+/) ? x.to_i : 1.0 / 0), x.to_s] }

这个想法是首先按数值排序,然后按字符串值排序。如果字符串不是以数值开头,则强制认为数值为无穷大。


编辑:正如 OP 所澄清的那样,他不仅要考虑前导数值,还要考虑后面的所有值,我们可以使用相同的想法,只是这次我们必须将其应用于每个字符串中的单个数字和非数字实体:

a.sort_by do |x|
  x.to_s.split(/(\D+)/).map do |y|
    [(y.match(/\d/) ? y.to_i : 1.0 / 0), y]
  end
end

【讨论】:

  • 数组中的0 最终会在"13a""a" 之间
  • 这样更好,但它不能正确排序["a13", "a2"]
  • @Stefan,再次更新。
最近更新 更多