场景:我有一个代码,可以根据下面的代码导出海龟坐标:
to path
file-open (word fileName ".csv")
file-print (word self xcor " " ycor)
file-close
end
结果类似于:
(turtle 1)[1 1 1 1 1 2] [4 4 4 2 1 5]
问:我如何导出这个相同的列表,但它的项目用逗号分隔?例如,从[1 2 1 1 1]
到[1,2,1,1,1]
。
提前感谢
发布于 2021-08-20 23:57:26
如果你想在事后用R或其他语言处理这个问题,我建议你可以使用长格式的报告(例如,每一行都表示一只乌龟,一个记号或类似的符号,以及坐标)--我觉得这样更容易处理。
为了回答你的实际问题,一种方法是手动将每个坐标列表折叠成逗号分隔的字符串。例如,请参阅下面的玩具模型。
简单设置:
extensions [csv]
globals [ test ]
turtles-own [ xcor-list ycor-list ]
to setup
ca
crt 10 [
set xcor-list []
set ycor-list []
]
repeat 5 [
ask turtles [
rt random 90 - 45
fd 1
set xcor-list lput pxcor xcor-list
set ycor-list lput pycor ycor-list
]
]
reset-ticks
end
这位记者实际上正在做的工作是将列表折叠成一个简单的字符串用于输出:
to-report collapse-string-list [str-list]
report reduce word ( sentence map [ str -> word str ", " ] but-last str-list last str-list )
end
此块将所需的海龟变量拉入列表中,调用列表上的collapse-string-list
报告器,然后导出为csv:
to output-coord-file
let all-turtles sort turtles
; Pull coordinates from each turtle
let who-coord-list map [
current-turtle ->
(list
[who] of current-turtle
collapse-string-list [xcor-list] of current-turtle
collapse-string-list [ycor-list] of current-turtle
)] all-turtles
; Add headers
set who-coord-list fput ["who" "x" "y"] who-coord-list
; Export
csv:to-file "toy.csv" (map [ row -> (map [i -> (word i)] row ) ] who-coord-list)
end
输出:
https://stackoverflow.com/questions/68868671
复制相似问题