|
|
1
43
红宝石<2.2
Ruby2.2引入了 Object#itself
作为一个猴子补丁
或作为
|
|
|
2
5
#!/usr/bin/ruby
a = Hash.new(0)
["1.111", "1.122", "1.250", "1.111"].each { |num|
a[num] += 1
}
a.max{ |a,b| a[1] <=> b[1] } # => ["1.111", 2]
或者,把它全部卷成一行: ary.inject(Hash.new(0)){ |h,i| h[i] += 1; h }.max{ |a,b| a[1] <=> b[1] } # => ["1.111", 2]
如果您只想返回项目,请添加.first(): ary.inject(Hash.new(0)){ |h,i| h[i] += 1; h }.max{ |a,b| a[1] <=> b[1] }.first # => "1.111"
#!/usr/bin/env ruby
require 'benchmark'
ary = ["1.111", "1.122", "1.250", "1.111"] * 1000
def most_common_value(a)
a.group_by { |e| e }.values.max_by { |values| values.size }.first
end
n = 1000
Benchmark.bm(20) do |x|
x.report("Hash.new(0)") do
n.times do
a = Hash.new(0)
ary.each { |num| a[num] += 1 }
a.max{ |a,b| a[1] <=> b[1] }.first
end
end
x.report("inject:") do
n.times do
ary.inject(Hash.new(0)){ |h,i| h[i] += 1; h }.max{ |a,b| a[1] <=> b[1] }.first
end
end
x.report("most_common_value():") do
n.times do
most_common_value(ary)
end
end
end
结果如下: user system total real Hash.new(0) 2.150000 0.000000 2.150000 ( 2.164180) inject: 2.440000 0.010000 2.450000 ( 2.451466) most_common_value(): 1.080000 0.000000 1.080000 ( 1.089784) |
|
3
4
|
|
4
2
如前所述,排序可能更快。 |
|
|
5
2
使用哈希的默认值功能:
|
|
|
6
0
它将返回数组中最常用的值
即:
|
|
|
Megrez7 · C#ToArray转换合并为一行,导致数组元素更改 1 年前 |
|
|
bairog · 从按属性筛选的对象数组字典中创建值数组 1 年前 |
|
|
Anka Hanım · 关于结构和动态数组地址的问题 1 年前 |
|
|
Geremia · 2D NumPy数组+1D数组? 1 年前 |
|
|
MARTIN · 交换第一个和最后一个单词,反转所有中间的字符 1 年前 |
|
|
Paul Williams · 迭代数组时输出有问题 1 年前 |