加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何索引数组中的重复项?

发布时间:2020-12-16 23:22:16 所属栏目:百科 来源:网络整理
导读:从以下数组(散列)开始: [ {:name="site a",:url="http://example.org/site/1/"},{:name="site b",:url="http://example.org/site/2/"},{:name="site c",:url="http://example.org/site/3/"},{:name="site d",{:name="site e",{:name="site f",:url="http://
从以下数组(散列)开始:
[
  {:name=>"site a",:url=>"http://example.org/site/1/"},{:name=>"site b",:url=>"http://example.org/site/2/"},{:name=>"site c",:url=>"http://example.org/site/3/"},{:name=>"site d",{:name=>"site e",{:name=>"site f",:url=>"http://example.org/site/6/"},{:name=>"site g",:url=>"http://example.org/site/1/"}
]

如何添加重复URL的索引,如下所示:

[
  {:name=>"site a",:url=>"http://example.org/site/1/",:index => 1},:url=>"http://example.org/site/2/",:url=>"http://example.org/site/3/",:index => 2},:url=>"http://example.org/site/6/",:index => 3}
]

解决方法

我会使用哈希来跟踪索引.
一次又一次地扫描先前的条目似乎效率低下
counts = Hash.new(0)
array.each { | hash | 
  hash[:index] = counts[hash[:url]] = counts[hash[:url]] + 1
}

还是有点干净

array.each_with_object(Hash.new(0)) { | hash,counts | 
  hash[:index] = counts[hash[:url]] = counts[hash[:url]] + 1
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读