双foreach循环
Double foreach loop
我有以下代码。
turtles-own [age]
set list1 (list 2 1 4 6)
set list2 (list (turtle 1) (turtle 0) (turtle 0) (turtle 0))
foreach list2 [ x ->
foreach list1 [ y ->
if (position x list2 = position y list1) [
ask x [ set age (item(position y list1) list1 ]
]
]
]
我想做的是遍历海龟列表和年龄列表。如果海龟的索引与值的索引匹配,则将海龟的年龄设置为该值。我在某种程度上工作,但似乎 list1 中的值以某种方式影响 foreach 循环。例如,我使用滑块来确定 list1 中的年龄值。列表 1 以 list1 (list a1 a2 a3 a4)
的形式编写,对于每个 a1、a2、a3、a4,我都有一个滑块。根据我在滑块上设置的值,一些海龟获得这些值,而其他海龟则没有t.Sometimes所有海龟获得年龄值,所有这些都取决于我使用幻灯片设置的值。
如果有更好的方法来做到这一点,那也会有所帮助。我所需要的只是使用一个循环,将年龄值设置为其相应的海龟。我有一个更大的海龟列表,这就是我需要使用循环的原因。
非常感谢。
position
仅报告列表中项目的第一个值。在此示例中,对于 foreach
循环中的每个 turtle 0
,position x list2
将报告 1。为了按原样工作,我认为您需要在每个列表是唯一的。
不太确定你在这里之后是什么,但我认为你可以通过在每个循环中包含一个计数器来解决你的问题,并使用它来比较索引值,以及设置 age
使用 item
:
turtles-own [age]
globals [ list1 list2 ]
to setup
ca
crt 2
set list1 (list 2 1 4 6)
set list2 (list (turtle 1) (turtle 0) (turtle 1) (turtle 0))
let l2counter 0
foreach list2 [ x ->
let l1counter 0
foreach list1 [ y ->
if l2counter = l1counter [
ask x [
set age item l1counter list1
show ( word "my age is now " age )
]
]
set l1counter l1counter + 1
]
set l2counter l2counter + 1
]
reset-ticks
end
编辑:
如果您不需要使用索引,这可能是更好的方法:
to setup-2
ca
crt 2
set list1 (list 2 1 4 6)
set list2 (list (turtle 1) (turtle 0) (turtle 1) (turtle 0))
( foreach list2 list1 [
[ _turt _age ] ->
ask _turt [
set age _age
]
]
)
end
我有以下代码。
turtles-own [age]
set list1 (list 2 1 4 6)
set list2 (list (turtle 1) (turtle 0) (turtle 0) (turtle 0))
foreach list2 [ x ->
foreach list1 [ y ->
if (position x list2 = position y list1) [
ask x [ set age (item(position y list1) list1 ]
]
]
]
我想做的是遍历海龟列表和年龄列表。如果海龟的索引与值的索引匹配,则将海龟的年龄设置为该值。我在某种程度上工作,但似乎 list1 中的值以某种方式影响 foreach 循环。例如,我使用滑块来确定 list1 中的年龄值。列表 1 以 list1 (list a1 a2 a3 a4)
的形式编写,对于每个 a1、a2、a3、a4,我都有一个滑块。根据我在滑块上设置的值,一些海龟获得这些值,而其他海龟则没有t.Sometimes所有海龟获得年龄值,所有这些都取决于我使用幻灯片设置的值。
如果有更好的方法来做到这一点,那也会有所帮助。我所需要的只是使用一个循环,将年龄值设置为其相应的海龟。我有一个更大的海龟列表,这就是我需要使用循环的原因。
非常感谢。
position
仅报告列表中项目的第一个值。在此示例中,对于 foreach
循环中的每个 turtle 0
,position x list2
将报告 1。为了按原样工作,我认为您需要在每个列表是唯一的。
不太确定你在这里之后是什么,但我认为你可以通过在每个循环中包含一个计数器来解决你的问题,并使用它来比较索引值,以及设置 age
使用 item
:
turtles-own [age]
globals [ list1 list2 ]
to setup
ca
crt 2
set list1 (list 2 1 4 6)
set list2 (list (turtle 1) (turtle 0) (turtle 1) (turtle 0))
let l2counter 0
foreach list2 [ x ->
let l1counter 0
foreach list1 [ y ->
if l2counter = l1counter [
ask x [
set age item l1counter list1
show ( word "my age is now " age )
]
]
set l1counter l1counter + 1
]
set l2counter l2counter + 1
]
reset-ticks
end
编辑:
如果您不需要使用索引,这可能是更好的方法:
to setup-2
ca
crt 2
set list1 (list 2 1 4 6)
set list2 (list (turtle 1) (turtle 0) (turtle 1) (turtle 0))
( foreach list2 list1 [
[ _turt _age ] ->
ask _turt [
set age _age
]
]
)
end