【问题标题】:read file lines with spaces into NetLogo as lists将带空格的文件行作为列表读入 NetLogo
【发布时间】:2012-04-20 10:54:26
【问题描述】:

如何将由空格分隔的文件内容作为列表读入 NetLogo? 例如,对于包含以下数据的文件:

  2321   23233  2  
  2321   3223   2
  2321   313    1
  213    321    1

我想创建如下列表:

a[2321,2321,2321,213]

b[23233,3223,313,321]

c[2,2,1,1]

【问题讨论】:

  • 你应该编辑你的问题,明确你希望第一个项目进入列表 a,第二个项目进入列表 b,等等。

标签: list file-io netlogo


【解决方案1】:

好吧,这是一种天真的方法:

let a []
let b []
let c []
file-open "data.txt"
while [ not file-at-end? ] [
  set a lput file-read a
  set b lput file-read b
  set c lput file-read c
]
file-close

它假定文件中的项目数是 3 的倍数。如果不是,您将遇到麻烦。

编辑:

...这里有一个更长,但也更通用和健壮的方法:

to-report read-file-into-list [ filename ]
  file-open filename
  let xs []
  while [ not file-at-end? ] [
    set xs lput file-read xs
  ]
  file-close
  report xs
end

to-report split-into-n-lists [ n xs ]
  let lists n-values n [[]]
  while [not empty? xs] [
    let items []
    repeat n [
      if not empty? xs [
        set items lput (first xs) items
        set xs but-first xs
      ]
    ]
    foreach (n-values length items [ ? ]) [
      set lists replace-item ? lists (lput (item ? items) (item ? lists))
    ]
  ]
  report lists
end

to setup
  let lists split-into-n-lists 3 read-file-into-list "data.txt"
  let a item 0 lists
  let b item 1 lists
  let c item 2 lists
end

【讨论】:

  • file-read 代码的变体是 read-from-string (word "[" file-read-line "]) — 这会产生一个值列表。该技巧是否适用取决于输入的格式,但它适用于 ZaC 的文件。
  • 您好,可以在netlogo中提供阅读列表的代码,找不到。
猜你喜欢
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-06
  • 1970-01-01
  • 2019-05-11
相关资源
最近更新 更多