我有这个数组:
arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]]
这里有一个代表包含列"a"、"b"和"c"的虾子表。
我该如何删除所有值5、8、1所在的整个"c"列?
"创建二维数组并访问Ruby子数组"和"修改Ruby二维数组的困难"中可能有有用的提示,但是我无法将它们转移到我的问题上。
我有这个数组:
arr = [["a","b","c"],[2,3,5],[3,6,8],[1,3,1]]
这里有一个代表包含列"a"、"b"和"c"的虾子表。
我该如何删除所有值5、8、1所在的整个"c"列?
"创建二维数组并访问Ruby子数组"和"修改Ruby二维数组的困难"中可能有有用的提示,但是我无法将它们转移到我的问题上。
出于好奇,这里提供另一种方法(一行代码):
arr.transpose[0..-2].transpose
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
因为只需使用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 }
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
# 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) }
我有一个更通用的需求,需要删除与文本模式匹配的一个或多个列(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]]
假设数组的第一个元素始终是列名的数组,则可以执行以下操作:
def delete_column(col, array)
index = array.first.index(col)
return unless index
array.each{ |a| a.delete_at(index) }
end
它将修改传入的数组。你不应该将其输出分配给任何东西。
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]]
arr.transpose[2]
即可返回该列。 - Mark Reedarr.transpose.last
或者arr.transpose[-1]
作为一种更通用的解决方案。 - TorimusArray#pop
,它会像我发布的那样很好地完成工作。 :) - Arup Rakshit