在二维数组中删除某一列的所有元素

5
8个回答

10

出于好奇,这里提供另一种方法(一行代码):

arr.transpose[0..-2].transpose

只需使用 arr.transpose[2] 即可返回该列。 - Mark Reed
1
@MarkReed 我更倾向于建议使用 arr.transpose.last 或者 arr.transpose[-1] 作为一种更通用的解决方案。 - Torimus
@MarkReed 我们有 Array#pop,它会像我发布的那样很好地完成工作。 :) - Arup Rakshit

3
 arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]]

 i = 2   # the index of the column you want to delete
 arr.each do |row|
   row.delete_at i
 end

  => [["a", "b"], [2, 3], [3, 6], [1, 3]] 

 class Matrix < Array
   def delete_column(i)
     arr.each do |row|
      row.delete_at i
     end
   end
 end

3

因为只需使用Array#pop就能获取最后一个值:

arr.each do |a|
  a.pop
end

或者找到"c"的索引并删除该索引处的所有元素:
c_index = arr[0].index "c"
arr.each do |a|
  a.delete_at c_index
end

或者使用map

c_index = arr[0].index "c"
arr.map{|a| a.delete_at c_index }

1
arr.map { |row| row.delete_at(2) } 
#=> ["c", 5, 8, 1]

如果您真的想要删除最后一列,以便它不再存在于原始数组中,那么可以这样做。如果您只想在保持 arr 不变的情况下返回它:
arr.map { |row| row[2] }
#=> ["c", 5, 8, 1]

如果您想删除与特定标题对应的列中的所有元素:
if index = arr.index('c') then
   arr.map { |row| row[index] }  # or arr.map { |row| row.delete_at(index) }
end

需要这样写:如果索引值等于arr[0]中字符'c'的索引值 - Jon Kern

1
# Assuming first row are headers
arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]]

col = arr.first.index "c"
arr.each { |a| a.delete_at(col) }

0

我有一个更通用的需求,需要删除与文本模式匹配的一个或多个列(s)(而不仅仅是删除最后一列)。

 col_to_delete = 'b'
 arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]]
 arr.transpose.collect{|a| a if (a[0] != col_to_delete)}.reject(&:nil?).transpose
 => [["a", "c"], [2, 5], [3, 8], [1, 1]] 

0

假设数组的第一个元素始终是列名的数组,则可以执行以下操作:

def delete_column(col, array)
  index = array.first.index(col)
  return unless index
  array.each{ |a| a.delete_at(index) }
end

它将修改传入的数组。你不应该将其输出分配给任何东西。


0
arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]]
arr.map(&:pop)
p arr #=> [["a", "b"], [2, 3], [3, 6], [1, 3]]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接