arr=[['a',2],['a',2],['a',-2],['b',3],['b',-3],['c',4]],要求将同种类中的正负抵消的项成对消除 result=[['a',2],['c',4]] 请指教!
@counter = {}
def count key, value
tmp = @counter[key]
@counter[key] = if tmp.nil?
value
else
tmp + value
end
end
@counter 里边的数据随时都是你要的结果
嗟,来食!
result = []
arr.each{|e|
if i = result.index([e[0], -e[1]])
result.delete_at i
else
result << e
end
}
#5 楼 @blacktulip 一行党
arr.inject([]){|r, a| (i = r.index [a[0], -a[1]]) && r.delete_at(i) ? r : r << a}
嗟,来跳坑!
a.sort.join(",").gsub(/(\w),-(\d),\1,\2,?/,"").split(",").each_slice(2).to_a