在AppleScript中按键查找记录


4

有没有办法通过其中一个键的值获得记录而不循环?

我一直这样做:

set theKey to 22

set theRecords to {{key:11, value:"foo"}, {key:22, value:"bar"}}
repeat with theRecord in theRecords
    if key of theRecord = theKey then
      display dialog (key of theRecord as text) & ":" & value of theRecord
    end if
end repeat

Answers:


3

我想你担心迭代的速度。迭代将是order-n O(n)的时间。

在AppleScript中,您可以使用记录记录而不是记录列表,但我相信密钥的类必须是标识符 - 而不是像示例中那样的整数。

这是一个有类似问题的人的链接: 在AppleScript中模拟关联数组

Lauri Ranta的答案是使用名为“awk”的命令行工具。

我玩弄的解决方案是创建一个不露面的后台应用程序,这个应用程序将被称为“代理”,AppleScript可以调用它来使用其数据结构,例如关联数组(也称为字典或映射)。

我没有完成我的解决方案。这只是一个想法,但你可以使用Lauri的答案,她通常知道她在说什么。

由于我知道一点Pyton,并且由于Pyton附带OS X,预先安装在系统文件夹中,我会考虑自己使用Python。

我在“纯AppleScript”中再次尝试使用以下代码,我对此并不满意:

set theRecords to {fooKey:{key:"fooKey", value:"fooValue"}, barKey:{key:"barKey", value:"barValue"}}
try
    set theRecord to get barKey of theRecords
    display dialog (key of theRecord & ":" & value of theRecord)
on error errorMessage number errorNumber
    if errorNumber is not equal to -128 then
        display dialog "No match"
    end if
end try

您可以混合使用shell脚本和AppleScripts:

-- in AppleScript, you can call a shell script
do shell script "<enter your shell script here>"

或者,您可以使用名为“osascript”的命令行工具从shell脚本调用AppleScript。


1
我有完全相同的问题。我不明白为什么AppleScript不允许以下单行:(every item in theRecords whose key is theKey)或(first item in theRecords whose key is theKey)。这将非常强大,类似于Python的列表推导。
— 比尔
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.