gpt4 book ai didi

list - 将带有空格的文件行作为列表读入 NetLogo

转载 作者:行者123 更新时间:2023-12-04 19:32:48 25 4
gpt4 key购买 nike

如何将空格分隔的文件内容作为列表读入 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]

最佳答案

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

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

关于list - 将带有空格的文件行作为列表读入 NetLogo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10244850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com