我在使用 GO 使用文本文件中的矩阵填充二维数组时遇到问题。
我遇到的主要问题是创建一个二维数组,因为我必须计算数组的维度,而 GO 似乎不接受数组维度中的 VAR:
nb_lines = number of line of the array
nb_col = number of columns of the array
// read matrix from file
whole_file,_ := ioutil.ReadFile("test2.txt")
// get each line of the file in tab_whole_file
tab_whole_file := strings.Split(string(whole_file), "\n")
// first line of the table
tab_first_line := strings.Split(tab_whole_file[0], "\t")
nb_col := len(tab_first_line)
nb_lines := len(tab_whole_file) - 1
// at this point I tried to build a array to contain the matrix values from the texte file
var columns [nb_lines][nb_col]float64 // does not work
columns := make([][]float64, nb_lines, nb_col) // does not work
columns := make([nb_lines][nb_col]float64) // does not work
columns := [nb_lines][nb_col]float64{} // does not work
columns := [][]float64{} // panic: runtime error: index out of range
for i := 0; i < nb_lines ; i++ { // for each line of the table from text file
line := strings.Split(tab_whole_file[0], "\t") // split one line to get each table values
for j := 1; j < len(line) ; j++ {
columns[i][j], _ = strconv.ParseFloat(line[j], 64) // assign each value to the table columns[i][j]
}
}
最佳答案
例如,
package main
import (
"bytes"
"fmt"
"io/ioutil"
"strconv"
)
func loadMatrix(filename string) ([][]float64, error) {
var m [][]float64
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
rows := bytes.Split(data, []byte{'\n'})
for r := len(rows) - 1; r >= 0; r-- {
if len(rows[r]) != 0 {
break
}
rows = rows[:len(rows)-1]
}
m = make([][]float64, len(rows))
nCols := 0
for r, row := range rows {
cols := bytes.Split(row, []byte{'\t'})
if r == 0 {
nCols = len(cols)
}
m[r] = make([]float64, nCols)
for c, col := range cols {
if c < nCols && len(col) > 0 {
e, err := strconv.ParseFloat(string(col), 64)
if err != nil {
return nil, err
}
m[r][c] = e
}
}
}
return m, nil
}
func main() {
filename := "matrix.tsv"
m, err := loadMatrix(filename)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Matrix:")
fmt.Println(m)
fmt.Println("\nBy [row,column]:")
for r := range m {
for c := range m[0] {
fmt.Printf("[%d,%d] %5v ", r, c, m[r][c])
}
fmt.Println()
}
fmt.Println("\nBy [column,row]:")
for c := range m[0] {
for r := range m {
fmt.Printf("[%d,%d] %5v ", c, r, m[r][c])
}
fmt.Println()
}
}
输出:
$ cat matrix.tsv
3.14 1.59 2.7 1.8
42
$ go run matrix.go
Matrix:
[[3.14 1.59 2.7 1.8] [42 0 0 0]]
By [row,column]:
[0,0] 3.14 [0,1] 1.59 [0,2] 2.7 [0,3] 1.8
[1,0] 42 [1,1] 0 [1,2] 0 [1,3] 0
By [column,row]:
[0,0] 3.14 [0,1] 42
[1,0] 1.59 [1,1] 0
[2,0] 2.7 [2,1] 0
[3,0] 1.8 [3,1] 0
$
关于arrays - 去 : how to Assign all elements in 2 by 2 array of variable size?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35970010/
我怎样才能完成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)
通过rubykoans.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
这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]
我已经搜索过这个问题的答案,但没有成功,有一个类似的问题,但答案在这种情况下不起作用,它按数字项目排序。SimilarQuestion-Thatdidnotwork我正在尝试使用ruby的sort_by对一个项目进行降序排序和另一个升序排序。我只能找到一个。代码如下:#PrimarysortLastNameDescending,withtiesbrokenbysortingAreaofinterest.people=people.sort_by{|a|[a.last_name,a.area_interest]}任何指导肯定会有所帮助。示例数据:输入罗素,逻辑欧拉,图论伽罗瓦,抽象代
通常,数组被实现为内存块,集合被实现为HashMap,有序集合被实现为跳跃列表。在Ruby中也是如此吗?我正在尝试从性能和内存占用方面评估Ruby中不同容器的使用情况 最佳答案 数组是Ruby核心库的一部分。每个Ruby实现都有自己的数组实现。Ruby语言规范只规定了Ruby数组的行为,并没有规定任何特定的实现策略。它甚至没有指定任何会强制或至少建议特定实现策略的性能约束。然而,大多数Rubyist对数组的性能特征有一些期望,这会迫使不符合它们的实现变得默默无闻,因为实际上没有人会使用它:插入、前置或追加以及删除元素的最坏情况步骤复
我正在使用Rails3.2.3和Ruby1.9.3p0。我发现我经常需要确定某个字符串是否出现在选项列表中。看来我可以使用Ruby数组.includemethod:或正则表达式equals-tildematchshorthand用竖线分隔选项:就性能而言,一个比另一个好吗?还有更好的方法吗? 最佳答案 总结:Array#include?包含String元素,在接受和拒绝输入时均胜出,对于您的示例只有三个可接受的值。对于要检查的更大的集合,看起来Set#include?和String元素可能会获胜。如何测试我们应该根据经验对此进行测试
给定两个大小相等的数组,如何找到不考虑位置的匹配元素的数量?例如:[0,0,5]和[0,5,5]将返回2的匹配项,因为有一个0和一个5共同;[1,0,0,3]和[0,0,1,4]将返回3的匹配项,因为0有两场,1有一场;[1,2,2,3]和[1,2,3,4]将返回3的匹配项。我尝试了很多想法,但它们都变得相当粗糙和令人费解。我猜想有一些不错的Ruby习惯用法,或者可能是一个正则表达式,可以很好地回答这个解决方案。 最佳答案 您可以使用count完成它:a.count{|e|index=b.index(e)andb.delete_at
我正在尝试循环哈希数组。当我到达获取枚举器开始循环的位置时,出现以下错误:undefinedmethod`[]'fornil:NilClass我的代码如下所示:defextraireAttributs(attributsParam)classeTrouvee=falsescanTrouve=falseownerOSTrouve=falseownerAppTrouve=falseresultat=Hash.new(0)attributs=Array(attributsParam)attributs.eachdo|attribut|#CRASHESHERE!!!typeAttribut=a
在我的Controller中,我得到了按类别分组的所有Extras:defindex@categories=Extra.all.group_by(&:category)end结果类似于哈希数组:{#=>[#,#=>[#,#]}我想按类别“排序”列而不是id排序,它应该如下所示:{#=>[#,#=>[#,#]}当我尝试时:defindex@categories=Extra.all.group_by(&:category).sort_by{|s|s[:sort]}end我得到“没有将符号隐式转换为整数”。那是因为我在“sort_by”中使用了一个符号吗? 最佳答
我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“