read file lines with spaces into NetLogo as lists

人走茶凉 提交于 2019-12-01 20:08:44

问题


How can I have file contents separated by spaces read into NetLogo as a list? For example, with a file containing data such as these:

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

I would like to create lists such as these:

a[2321,2321,2321,213]

b[23233,3223,313,321]

c[2,2,1,1]

回答1:


Well, here is a naive way to do it:

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

It assumes the number of items in your file is a multiple of 3. You will run into trouble if it isn't.

Edit:

...and here is a much longer, but also more general and robust way to do it:

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


来源:https://stackoverflow.com/questions/10244850/read-file-lines-with-spaces-into-netlogo-as-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!