我对从此代码创建的海龟数量有疑问:
to read-turtles-from-csv
file-close-all ; close all open files
if not file-exists? "turtles.csv" [
user-message "No file 'turtles.csv' exists! Try pressing WRITE-TURTLES-TO-CSV."
stop
]
file-open "turtles.csv" ; open the file with the turtle data
; We'll read all the data in a single loop
while [ not file-at-end? ] [
let data csv:from-row file-read-line
create-turtles 1 [
print "item column 4"
show item 4 data
]
]
file-close ; make sure to close the file
end
我的turtles.csv文件只有两行,所以我在这里预期的是,对于行数重复创建-turtles 1,我有两个代理,第4列中的2个数字被打印出来。令人惊讶的是,创造了4只乌龟!为什么呢?
由于
答案 0 :(得分:2)
我想知道你的turtles.csv
是否被读入的行数多于应有的数量?尝试做类似的事情:
to read-file
file-close-all
file-open "turtles.csv"
while [not file-at-end?] [
print csv:from-row file-read-line
]
file-close-all
end
了解Netlogo如何读取文件。看起来你是在正确的轨道上,否则 - 我只是按照你的例子测试了一个类似的文件,我按照预期得到了两只乌龟。使用名为“turtle_details.csv”的.csv
文件,如下所示:
color size heading
1 red 2 90
2 blue 4 180
我使用此代码生成两个包含.csv
中的变量的海龟:
extensions [ csv ]
to setup
ca
reset-ticks
file-close-all
file-open "turtle_details.csv"
;; To skip the header row in the while loop,
; read the header row here to move the cursor
; down to the next line.
let headings csv:from-row file-read-line
while [ not file-at-end? ] [
let data csv:from-row file-read-line
print data
create-turtles 1 [
set color read-from-string item 0 data
set size item 1 data
set heading item 2 data
]
]
file-close-all
end