【发布时间】:2015-08-19 04:48:32
【问题描述】:
如何在 ruby 中找到具有特定值的数组中所有元素的索引?
IE。如果你有一个数组 [2,3,52,2,4,1,2],有没有比使用循环更简单的方法来获取数组中所有 2 的索引?因此,如果我要寻找 2,答案将类似于 [0,3,6]。
答案在
Get index of array element faster than O(n)
如果我只想找到给定元素的一个实例,则给出解决方案。
【问题讨论】:
如何在 ruby 中找到具有特定值的数组中所有元素的索引?
IE。如果你有一个数组 [2,3,52,2,4,1,2],有没有比使用循环更简单的方法来获取数组中所有 2 的索引?因此,如果我要寻找 2,答案将类似于 [0,3,6]。
答案在
Get index of array element faster than O(n)
如果我只想找到给定元素的一个实例,则给出解决方案。
【问题讨论】:
试试这个,
arr = [2,3,52,2,4,1,2]
output = []
arr.each_with_index do |v,i|
if v == 2
output << i
end
end
puts output #=> [0, 3, 6]
【讨论】:
a
# => [2, 3, 52, 2, 4, 1, 2]
b = []
# => []
a.each_with_index{|i, ind| b << ind if i == 2}
# => [2, 3, 52, 2, 4, 1, 2]
【讨论】:
也许你可以用这个:
a = [2, 3, 52, 2, 4, 1, 2]
b = a.map.with_index{|k, i| i if k == 2}.compact
b
# => [0,3,6]
或者如果您想修改变量,请修改版本。
a = [2, 3, 52, 2, 4, 1, 2]
a.map!.with_index{|k, i| i if k == 2}.compact!
a
# => [0,3,6]
【讨论】:
b,为什么要使用map?您正在将 a 映射到您不使用的数组。 a.each_with_index不是更直接吗?
a.each_with_object([]).find_all {|i, index| i == 2}.map {|i, index| index }
我觉得还是有捷径的。
另一个选项可能是:
a.each_with_object([]).with_index {|(i, result), index| result << index if i == 2 }
【讨论】:
a = [2,3,52,2,4,1,2]
a.each_index.select { |i| a[i]== 2 }
#=> [0, 3, 6]
【讨论】: