我尝试了:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
我原本期望
["some", "thing", "another", "thing"]
但实际得到的是
["some", "thing", nil]
我尝试了:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)
我原本期望
["some", "thing", "another", "thing"]
但实际得到的是
["some", "thing", nil]
另一种做法而已。
[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]
flatten
尽可能地递归地将所有内容压平,甚至包括嵌套的数组。因此,如果somearray
或anotherarray
包含嵌套的数组,它们也会被压平。这是一个通常不打算发生的副作用。 - hagelloconcat
或+
,几乎每个答案都提到了这一点。[[a, b], | [[x], [[a, b, x],
[c, d]] | [y]] => [c, d, y]]
each_with_index
。相反,我结合使用zip和flatten,如下所示:# given two multi-dimensional arrays that you want to concatenate row-wise
m1 = [[:a, :b], [:c, :d]]
m2 = [[:x], [:y]]
m1m2 = m1.zip(m2).map(&:flatten)
# => [[:a, :b, :x], [:c, :d, :y]]
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray + anotherarray # => ["some", "thing", "another", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]
somearray.push(anotherarray).flatten # => ["some", "thing", "another", "thing"]
somearray.push *anotherarray # => ["another", "thing", "another", "thing"]
1.9.3-p551 :020 > a = [1, 2]
=> [1, 2]
1.9.3-p551 :021 > b = [3, 4]
=> [3, 4]
1.9.3-p551 :022 > c = 5
=> 5
1.9.3-p551 :023 > a.object_id
=> 6617020
1.9.3-p551 :024 > a.push *b
=> [1, 2, 3, 4]
1.9.3-p551 :025 > a.object_id
=> 6617020
1.9.3-p551 :026 > a.push *c
=> [1, 2, 3, 4, 5]
1.9.3-p551 :027 > a.object_id
=> 6617020
a = ['a', 'b']
b = ['c', 'd']
arr = [a, b].flatten
这不会删除重复项,但是
a|b
删除重复项。
我很惊讶没有人提到reduce
,当你有一个数组的数组时,它可以很好地工作:
lists = [["a", "b"], ["c", "d"]]
flatlist = lists.reduce(:+) # ["a", "b", "c", "d"]
somearray = ["一些", "东西"]
anotherarray = ["另一些", "东西"]
somearray + anotherarray
我发现将数组推入或添加到另一个数组中,然后在原地展平它们更容易,就像这样:
somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push anotherarray # => ["some", "thing", ["another", "thing"]]
#or
somearray << anotherarray # => ["some", "thing", ["another", "thing"]]
somearray.flatten! # => ["some", "thing", "another", "thing"]
somearray # => ["some", "thing", "another", "thing"]
Array#flatten!
是“原地”将数组压平。如果没有进行修改(即数组不包含子数组),则返回nil。 - yeyoflatten!
的工作方式不同,所以没有得到。最后,这个问题反映了一个逻辑问题而不是一个优化问题。请参见下面pilcrow的答案获取更多信息。 - yeyo