使用 Ruby 查找 X 文件中的公共行

发布于 2024-09-13 01:50:22 字数 279 浏览 1 评论 0原文

现在我有 3 个文件,但我想以一种稍后可以添加更多文件的方式执行此操作。每个文件都是一个 ID 列表,如下所示。

174535945 174538045 160515924 81712260 25241494

我希望输出是列表 1 和列表 2、列表 2 和列表 3 中出现的项目,以及列表 1、列表 2 和列表 3 中出现的项目。

创建哈希的最红宝石方式是每个列表都有一个密钥,然后获取所有密钥并针对所有哈希进行测试,或者是否有一个很好的 gem 可以帮助解决这个问题?

谢谢,

Right now I have 3 files, but I'd like to do this in a way that I can add more later. Each file is a list of IDs, like this.

174535945
174538045
160515924
81712260
25241494

I'd like the output to be the items that appear in list 1 and list 2, list 2 and list 3, and those that occur in list 1 and list 2 and list 3.

Would the most ruby way to be create a hash with a key for each list, and then get all keys and test against all hashes, or is there a nice gem that would help with this?

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情栀口红 2024-09-20 01:50:22

使用套装:

require 'set'

list_1 = open(filename_1).read.split.to_set
list_2 = open(filename_2).read.split.to_set
list_3 = open(filename_3).read.split.to_set

puts list_1 & list_2
puts list_2 & list_3
puts list_1 & list_2 & list_3

Use sets:

require 'set'

list_1 = open(filename_1).read.split.to_set
list_2 = open(filename_2).read.split.to_set
list_3 = open(filename_3).read.split.to_set

puts list_1 & list_2
puts list_2 & list_3
puts list_1 & list_2 & list_3
小…红帽 2024-09-20 01:50:22

我认为您使用哈希的建议是可行的方法:

require 'set'

class Test
  def initialize()
    @lists = {174=>[1,2,3], 111=>[2,3,4], 160=>[2,4,5]}
  end

  def common_members(*keys)
    lists_as_sets = {}
    @lists.each_pair {|key,list| lists_as_sets[key] = list.to_set}
    common = lists_as_sets[keys.shift] # Set to key[0] and nil that element of keys
    keys.each {|k| common = common & lists_as_sets[k]} # Intersect the remaining keys, if any
    common.to_a
  end
end

t = Test.new
p t.common_members(174,111) # => [2,3]
p t.common_members(111,160) # => [2,4]
p t.common_members(174,111,160) # =>[2]

I think your suggestion of using a hash is the way to go:

require 'set'

class Test
  def initialize()
    @lists = {174=>[1,2,3], 111=>[2,3,4], 160=>[2,4,5]}
  end

  def common_members(*keys)
    lists_as_sets = {}
    @lists.each_pair {|key,list| lists_as_sets[key] = list.to_set}
    common = lists_as_sets[keys.shift] # Set to key[0] and nil that element of keys
    keys.each {|k| common = common & lists_as_sets[k]} # Intersect the remaining keys, if any
    common.to_a
  end
end

t = Test.new
p t.common_members(174,111) # => [2,3]
p t.common_members(111,160) # => [2,4]
p t.common_members(174,111,160) # =>[2]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文