programing

루비의 다른 배열에 배열을 추가하고 다차원 결과로 끝나지 않으려면 어떻게 해야 합니까?

kakaobank 2023. 5. 17. 23:19
반응형

루비의 다른 배열에 배열을 추가하고 다차원 결과로 끝나지 않으려면 어떻게 해야 합니까?

노력했습니다.

somearray = ["some", "thing"]
anotherarray = ["another", "thing"]
somearray.push(anotherarray.flatten!)

나는 예상했습니다.

["some", "thing", "another", "thing"]

그러나 받았습니다.

["some", "thing", nil]

당신은 실행 가능한 아이디어를 가지고 있지만,#flatten!잘못된 위치에 있습니다. 수신기를 평평하게 하여 회전시키는 데 사용할 수 있습니다.[1, 2, ['foo', 'bar']]안으로[1,2,'foo','bar'].

분명히 몇 가지 접근법을 잊고 있지만, 다음과 같이 연결할 수 있습니다.

a1.concat a2
a1 + a2              # creates a new array, as does a1 += a2

또는 추가/삭제:

a1.push(*a2)         # note the asterisk
a2.unshift(*a1)      # note the asterisk, and that a2 is the receiver

또는 스플라이스:

a1[a1.length, 0] = a2
a1[a1.length..0] = a2
a1.insert(a1.length, *a2)

또는 추가 및 평탄화:

(a1 << a2).flatten!  # a call to #flatten instead would return a new array

그사용수있다니습할냥▁use▁the를 사용하면 됩니다.+교환원!

irb(main):001:0> a = [1,2]
=> [1, 2]
irb(main):002:0> b = [3,4]
=> [3, 4]
irb(main):003:0> a + b
=> [1, 2, 3, 4]

어레이 클래스에 대한 모든 내용은 http://ruby-doc.org/core/classes/Array.html 에서 확인할 수 있습니다.

가장 깨끗한 방법은 Array#concat 메서드를 사용하는 것입니다. 이 메서드는 새 배열을 생성하지 않습니다(같은 작업을 수행하지만 새 배열을 생성하는 Array#+와 달리).

문서에서 직접(http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-concat) :

concat(기타_ary)

other_ary의 요소를 self에 추가합니다.

그렇게

[1,2].concat([3,4])  #=> [1,2,3,4]  

Array#concat는 다차원 배열이 인수로 전달되는 경우 평평하지 않습니다.이 문제는 별도로 처리해야 합니다.

arr= [3,[4,5]]
arr= arr.flatten   #=> [3,4,5]
[1,2].concat(arr)  #=> [1,2,3,4,5]

마지막으로 Ruby core 클래스에 유용한 도우미를 추가하는 corelib gem(https://github.com/corlewsolutions/corelib) 을 사용할 수 있습니다.특히 콘캣을 실행하기 전에 다차원 배열을 자동으로 평평하게 만드는 Array#add_all 메서드가 있습니다.

a = ["some", "thing"]
b = ["another", "thing"]

가기하를 추가하는 ba를 결를저장니다합에 저장합니다.a:

a.push(*b)

또는

a += b

경우든, 어느쪽든이.a다음이 됩니다.

["some", "thing", "another", "thing"]

만전경우의은, 들소요의 이.b의 시존템추니에 됩니다.a 두 가 열, 그, 배에 됩니다.a.

Ruby 버전 >= 2.0에서는 작동하지만 이전 버전에서는 작동하지 않는 쉬운 방법:

irb(main):001:0> a=[1,2]
=> [1, 2]
irb(main):003:0> b=[3,4]
=> [3, 4]
irb(main):002:0> c=[5,6]
=> [5, 6]
irb(main):004:0> [*a,*b,*c]
=> [1, 2, 3, 4, 5, 6]

두 가지 방법이 있습니다. 이 경우 첫 번째 방법은 새 배열을 할당합니다(일부 배열 = 일부 배열 + 다른 배열로 변환됨).

somearray = ["some", "thing"]

anotherarray = ["another", "thing"]

somearray += anotherarray # => ["some", "thing", "another", "thing"]

somearray = ["some", "thing"]
somearray.concat anotherarray # => ["some", "thing", "another", "thing"]

시도해 보십시오. 어레이를 결합하여 중복 항목을 제거합니다.

array1 = ["foo", "bar"]
array2 = ["foo1", "bar1"]

array3 = array1|array2

http://www.ruby-doc.org/core/classes/Array.html

"Set Union"에 대한 자세한 문서 보기

(array1 + array2).uniq

이렇게 하면 먼저 배열 1 요소를 얻을 수 있습니다.중복되지 않습니다.

@을 자세히은 @Pilcrow 대답자세히설명거면하대배한다같열습니적다대답과음유은일한의합한에을▁@▁elabor▁suitable▁forpil▁onlypil다▁is▁answer니▁arrays같습'ating▁thes▁huge▁answer▁@▁on다과음의crowcrow답대은입니다.concat(+는 루프 때새 때문입니다.)는 루프 내부에서 작동할 때 가비지 제거할 새 개체를 할당하지 않고 속도가 빠릅니다.

벤치마크는 다음과 같습니다.

require 'benchmark'

huge_ary_1 = Array.new(1_000_000) { rand(5_000_000..30_000_00) }

huge_ary_2 = Array.new(1_000_000) { rand(35_000_000..55_000_00) }

Benchmark.bm do |bm|
  p '-------------------CONCAT ----------------'
  bm.report { huge_ary_1.concat(huge_ary_2) }

  p '------------------- PUSH ----------------'
  bm.report { huge_ary_1.push(*huge_ary_2)  }
end

결과:

       user     system      total        real
"-------------------CONCAT ----------------"
  0.000000   0.000000   0.000000 (  0.009388)
"------------------- PUSH ----------------"
  example/array_concat_vs_push.rb:13:in `block (2 levels) in <main>': stack level too deep (SystemStackError)

를 사용하여 확인할 수 있습니다.push오류 발생:stack level too deep (SystemStackError)어레이가 충분히 큰 경우.

["some", "thing"] + ["another", "thing"]

다른 방법일 뿐입니다.

[somearray, anotherarray].flatten
=> ["some", "thing", "another", "thing"]

문제는 본질적으로 "Ruby에서 어레이를 연결하는 방법"입니다.당연히 답은 사용하는 것입니다.concat또는+거의 모든 회답에서 언급한 바야흐로

질문의 자연스러운 확장은 "Ruby에서 2D 배열의 행별 연결을 수행하는 방법"입니다.제가 "루비 연결 행렬"을 구글에 검색했을 때, 이 SO 질문이 최고의 결과였기 때문에 저는 후손들을 위해 그 질문(묻지는 않았지만 관련이 있는)에 대한 제 대답을 여기에 남기기로 생각했습니다.


일부 애플리케이션에서는 두 개의 2D 어레이를 행 단위로 "연결"할 수 있습니다.뭐 그런 거.

[[a, b], | [[x],    [[a, b, x],
 [c, d]] |  [y]] =>  [c, d, y]]

이것은 행렬을 "증강"하는 것과 같습니다.예를 들어, 저는 이 기술을 사용하여 여러 개의 더 작은 행렬로 그래프를 나타내는 단일 인접 행렬을 만들었습니다.이 기술이 없었다면 구성 요소에 대해 오류가 발생하기 쉬우거나 생각하기에 답답할 수 있는 방식으로 반복해야 했을 것입니다.제가 해야 했을 수도 있어요.each_with_index,예를들면.대신 zip과 flat을 다음과 같이 결합하였습니다.

# 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 

아무도 언급하지 않은 것이 놀랍습니다.reduce어레이가 있는 경우 다음과 같은 이점이 있습니다.

lists = [["a", "b"], ["c", "d"]]
flatlist = lists.reduce(:+)  # ["a", "b", "c", "d"]
a = ['a', 'b']
b = ['c', 'd']
arr = [a, b].flatten

이렇게 하면 멍청이들을 제거할 수는 없지만,

a|b

백업을 제거합니다.

some array = ["some", "thing"]

another array = ["another", "thing"]

일부 배열 + 다른 배열

어레이를 푸시하거나 추가한 다음 제자리에서 평평하게 만드는 것이 더 쉽다는 것을 알게 되었습니다.

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"]

언급URL : https://stackoverflow.com/questions/1801516/how-do-you-add-an-array-to-another-array-in-ruby-and-not-end-up-with-a-multi-dim

반응형