【问题标题】:How to flatten subarrays in Ruby?如何在 Ruby 中展平子数组?
【发布时间】:2017-01-14 21:03:30
【问题描述】:

我有以下结构

a = [['a', 'b', 'c'], ['d', 'e', 'f'], [['g', 'h', 'i'], ['l', 'm', 'n']]]

我想获得以下内容:

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]

我尝试了以下方法:

a.flatten => ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'l', 'm', 'n']

a.flatten(1) => ['a', 'b', 'c', 'd', 'e', 'f', ['g', 'h', 'i'], ['l', 'm', 'n']]

我目前找到的解决方案是将初始结构更改为这种格式:

b = [[['a', 'b', 'c']], [['d', 'e', 'f']], [['g', 'h', 'i'], ['l', 'm', 'n']]]

然后调用

b.flatten(1) => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]

但我可以这样做只是因为我能够更改 a 的构建方式。我的问题仍然存在:如何从a 开始获得我想要的结果?

【问题讨论】:

  • 如果您知道您需要/拥有三元组(大小为 3 的数组),我会选择一个无法回答您问题的解决方案 :) 和 flatten 然后切片。
  • 不,每个数组里面的元素个数不固定,数组和子数组的个数也一样

标签: arrays ruby flatten


【解决方案1】:
a.each_with_object([]) do |e, memo|
  e == e.flatten ? memo << e : e.each { |e| memo << e }
end
#⇒ [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]

【讨论】:

  • 期待更优雅的东西,但您的解决方案运行良好。
【解决方案2】:

其他解决方案:

a.flat_map { |e| e[0].is_a?(Array) ? e : [e] }
#=> [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["l", "m", "n"]]

【讨论】:

  • a.flat_map { |e| e.flatten == e ? [e] : e } 也可以
  • Array#flat? 在这里会很方便。
  • @coorasse,只检查第一个元素而不是转换所有数组然后检查更有效
  • @Stefan,你能给出这个方法文档的链接吗?我找不到它。
  • 哦,它不存在。我想说这样的方法会很有用。
猜你喜欢
  • 1970-01-01
  • 2012-11-14
  • 2017-05-15
  • 2014-05-21
  • 2011-12-14
  • 2019-11-16
  • 1970-01-01
  • 2017-07-11
  • 1970-01-01
相关资源
最近更新 更多