簡體   English   中英

映射數組中與特定值匹配的值的索引?

[英]Mapping the index of values in an array that match a specific value?

免責聲明,我是初學者。

我有一個16位數的數組,限制為0和1。 我正在嘗試創建一個新數組,其中只包含原始數組中1的索引值。

我目前有:

one_pos = []
    image_flat.each do |x| 
        if x == 1 
            p = image_flat.index(x)
            one_pos << p
            image_flat.at(p).replace(0)
        end
    end

image_flat數組為[0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0]

使用上面的代碼,one_pos返回[3,3]而不是我期望的[3,5]。

我哪里錯了?

我哪里錯了?

你打電話時

image_flat.index(x)

它只返回image_flat數組中x的第一個條目。

我想有一些像這樣的更好的解決方案:

image_flat.each_with_index do |v, i|
  one_pos << i if v == 1
end

嘗試在陣列上使用each_with_index( http://apidock.com/ruby/Enumerable/each_with_index )。

image_flat = [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

one_pos = []
image_flat.each_with_index do |value, index| 
  if value == 1 
    one_pos << index
  end
end

我認為這是最優雅的解決方案:

image_flat.each_index.select{|i| image_flat[i] == 1}

如果您正在尋找一種無法從可枚舉塊中獲取的解決方案,這是一個解決方案,盡管它確實需要鏈式解決方案。

image_flat.each_with_index.select { |im,i| im==1 }.map { |arr| arr[1] }

它的鏈接將需要額外的查找,因此Gena Shumilkin的答案可能更適合更大的陣列。

這是我最初認為Gena Shumilkin試圖達到的目標,直到我意識到解決方案使用each_index而不是each_with_index。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM