草庐IT

arrays - 计算相似的数组值

coder 2024-07-08 原文

我正在尝试学习 Go(或 Golang),但似乎无法正确学习。我有 2 个文本文件,每个文件都包含一个单词列表。我正在尝试计算两个文件中出现的单词数量。

到目前为止,这是我的代码:

package main

import (
    "fmt"
    "log"
    "net/http"
    "bufio"
)

func stringInSlice(str string, list []string) bool {
    for _, v := range list {
        if v == str {
            return true
        }
    }
    return false
}

func main() {
    // Texts URL
    var list = "https://gist.githubusercontent.com/alexcesaro/c9c47c638252e21bd82c/raw/bd031237a56ae6691145b4df5617c385dffe930d/list.txt"
    var url1 = "https://gist.githubusercontent.com/alexcesaro/4ebfa5a9548d053dddb2/raw/abb8525774b63f342e5173d1af89e47a7a39cd2d/file1.txt"

    //Create storing arrays
    var buffer [2000]string
    var bufferUrl1 [40000]string

    // Set a sibling counter
    var sibling = 0

    // Read and store text files
    wordList, err := http.Get(list)
    if err != nil {
        log.Fatalf("Error while getting the url : %v", err)
    }
    defer wordList.Body.Close()

    wordUrl1, err := http.Get(url1)
    if err != nil {
        log.Fatalf("Error while getting the url : %v", err)
    }
    defer wordUrl1.Body.Close()

    streamList := bufio.NewScanner(wordList.Body)
    streamUrl1 := bufio.NewScanner(wordUrl1.Body)

    streamList.Split(bufio.ScanLines)
    streamUrl1.Split(bufio.ScanLines)

    var i = 0;
    var j = 0;

    //Fill arrays with each lines
    for streamList.Scan() {
        buffer[i] = streamList.Text()
        i++
    }
    for streamUrl1.Scan() {
        bufferUrl1[j] = streamUrl1.Text()
        j++
    }

    //ERROR OCCURRING HERE :
    // This code if i'm not wrong is supposed to compare through all the range of bufferUrl1 -> bufferUrl1 values with buffer values, then increment sibling and output FIND
    for v := range bufferUrl1{
        if stringInSlice(bufferUrl1, buffer) {
            sibling++
            fmt.Println("FIND")
        }
    }

    // As a testing purpose thoses lines properly paste both array
    // fmt.Println(buffer)
    // fmt.Println(bufferUrl1)

}

但现在,我的构建甚至没有成功。我只收到这条消息:

.\hello.go:69: cannot use bufferUrl1 (type [40000]string) as type string in argument to stringInSlice
.\hello.go:69: cannot use buffer (type [2000]string) as type []string in argument to stringInSlice

最佳答案

  1. bufferUrl1 是一个数组:[4000]string。您打算使用 v(每个 bufferUrl1 中的字符串)。但事实上,你打算用第二个 变量——第一个变量是在代码中被忽略的索引 下面使用 _
  2. type [2000]string 不同于 []string。在 Go 中,数组和 slice 是不一样的。阅读Go Slices: usage and internals .我已经使用 make 更改了两个变量声明以使用具有相同初始长度的 slice 。

这些是您需要进行编译的更改。

声明:

// Create storing slices
buffer := make([]string, 2000)
bufferUrl1 := make([]string, 40000)

第 69 行的循环:

for _, s := range bufferUrl1 {
    if stringInSlice(s, buffer) {
        sibling++
        fmt.Println("FIND")
    }
}

作为旁注,考虑使用映射而不是 buffer 的 slice 来更有效地查找,而不是循环遍历 stringInSlice 中的列表。

https://play.golang.org/p/UcaSVwYcIw修复了下面的评论(您将无法从 Playground 发出 HTTP 请求)。

关于arrays - 计算相似的数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36534813/

有关arrays - 计算相似的数组值的更多相关文章

  1. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  4. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  5. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  6. Ruby Koans about_array_assignment - 非平行与平行分配歧视 - 2

    通过ruby​​koans.com,我在about_array_assignment.rb中遇到了这两段代码你怎么知道第一个是非并行赋值,第二个是一个变量的并行赋值?在我看来,除了命名差异之外,代码几乎完全相同。4deftest_non_parallel_assignment5names=["John","Smith"]6assert_equal["John","Smith"],names7end45deftest_parallel_assignment_with_one_variable46first_name,=["John","Smith"]47assert_equal'John

  7. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  8. ruby-on-rails - 使用一系列等级计算字母等级 - 2

    这里是Ruby新手。完成一些练习后碰壁了。练习:计算一系列成绩的字母等级创建一个方法get_grade来接受测试分数数组。数组中的每个分数应介于0和100之间,其中100是最大分数。计算平均分并将字母等级作为字符串返回,即“A”、“B”、“C”、“D”、“E”或“F”。我一直返回错误:avg.rb:1:syntaxerror,unexpectedtLBRACK,expecting')'defget_grade([100,90,80])^avg.rb:1:syntaxerror,unexpected')',expecting$end这是我目前所拥有的。我想坚持使用下面的方法或.join,

  9. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

  10. ruby - 在 Ruby 中用键盘诅咒数组浏览 - 2

    我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作

随机推荐