NETLOGO:读取从matlab导出的csv文件并将其存储为列表列表

问题描述 投票:0回答:1

我试图读取从matlab导出的csv文件,其中包含35040行和5列(此文件的每个元素都是一个数字)。之后我想将这样的文件存储为Netlogo中的列表列表。我试图这样做的方式是:

globals[mylist]

set mylist (csv:from-file "output.csv" )
show mylist

此代码实际上读取csv文件并将其保存为类型列表的列表:

[[a1 a2 a3 a4 a5] [b1 b2 b3 b4 b5]]

问题是每个嵌套列表的最后一个元素最后都存有一系列分号。例如,在第一个嵌套列表中,最后一个元素应该是0.7980,但它存储为“0.7980 ;;;;;;;;;;;”所以作为一个字符串。我该如何解决?这是与我正在阅读的csv文件相关的问题还是我正在使用的代码有问题?我该怎么办?

csv netlogo nested-lists
1个回答
2
投票

是的,问题在于您的CSV文件,并且根据其来源,最佳解决方案可能是在源文件中修复它。

话虽这么说,你也可以在NetLogo中以一种摆脱分号的方式处理它。以下是如何执行此操作的示例:

to demo
  let list-of-lists [[1 2 3 4 "5;;;;"] [6 7 8 9 "10;;;;;"]]
  let new-list-of-lists map [ xs -> map parse xs ] list-of-lists
  print word "Old list: " list-of-lists
  print word "New list: " new-list-of-lists
end

to-report parse [ value ]  
  report ifelse-value (is-string? value and (position ";" value != false)) [
    ; if the value is a string containing a ";", take the string
    ; up to the position of the ";" and try to convert it to a number
    read-from-string substring value 0 position ";" value
  ] [
    ; otherwise, leave the value alone
    value
  ]
end

这不是世界上最强大的代码,但如果您的文件遵循常规格式,它可以工作。如果没有,您可以随时根据具体情况进行调整。

除了map,这里使用的关键原语是positionread-from-string。如果你在字典中查找它们,你应该能够弄清楚它是如何工作的......

© www.soinside.com 2019 - 2024. All rights reserved.