Applescript 处理程序,用 i 重复从 1 到 this_list 的数量

Applescript handler, repeat with i from 1 to the number of this_list

如果有人能告诉我我在这里做错了什么,或者指出正确的方向以找到答案,我将不胜感激。

我有一个号码列表,以及一个相应名称的列表

numList {"1", "2", "4", "6"}
nameList {"bob", "joel", "mickey", "tara", "jason", "stacey"}

我正在尝试创建一个处理程序来从 numList 中获取数字并将相应的名称作为列表获取。

The result should be {"bob", "joel", "tara", "stacey"

这是我的,但是 return 名字不正确。

on myFirstHandler(this_list, other_list)
    set rest_list to {}
    set availlist to {}
    repeat with h from 1 to the number of this_list
        set the rest_list to item h of other_list
        set the end of the availlist to rest_list
    end repeat
    return availlist
end myFirstHandler

set numList {"1", "2", "4", "6"}
set nameList {"bob", "joel", "mickey", "tara", "jason", "stacey"}

myFirstHandler(numList, nameList)
set AlcoholAvailable to the result

returns {"bob", "joel", "mickey", "tara"}

您的尝试非常非常接近。这是它的修改、更正版本:

on myFirstHandler(this_list, other_list)
    set rest_list to {}

    repeat with h in this_list
        set the end of rest_list to item h of other_list
    end repeat

    return rest_list
end myFirstHandler


set numList to {1, 2, 4, 6}
set nameList to {"bob", "joel", "mickey", "tara", "jason", "stacey"}

myFirstHandler(numList, nameList)
set AlcoholAvailable to the result

主要的关键区别在于 repeat 循环的定义方式:在您最初的尝试中,您在 indices,因此您总是要使用 运行 1, 2, 3, 4, 5, 6 的数字,因此,从目标列表中提取这些项目。在我的修改版本中,我循环遍历 values,因此我能够使用源列表中的数字 1, 2, 4, 6.

所以比较一下你的 repeat 子句:

repeat with h from 1 to the number of this_list

和我的一样:

repeat with h in this_list

两者都是 AppleScript 的完全有效位,但做的事情略有不同:一个使用 indices,另一个使用 values.


一种稍微高级但更加通用的方法是这样的:

set numList to {1, 2, 4, 6}
set nameList to {"bob", "joel", "mickey", "tara", "jason", "stacey"}

on map(L, function)
    local L, function

    tell result to repeat with x in L
        set x's contents to function's fn(x)
    end repeat

    L
end map

on itemInList(L)
    script
        on fn(x)
            item x of L
        end fn
    end script
end itemInList

map(numList, itemInList(nameList))

在这里,我定义了一个"basic" mapping函数。 mapping 函数接受一个函数——在这种情况下,returns 目标列表中的一个元素——并将该函数应用于数组中的每个元素——在这种情况下,你的源列表,numList。此列表在此过程中被修改,因此您会发现 numList 的元素已替换为 {"bob", "joel", "tara", "stacey"}

这个构造的特别之处在于,您可以替换 map 在本示例中使用的函数(处理程序),itemInList() 并定义其他具有类似性质的处理程序,这些处理程序可以对您的列表。