在AppleScript中同时循环2个数组

时间:2014-05-20 22:48:47

标签: loops applescript

说我有:

set U = { "a", "b", "c" }
set V = { 1, 2, 3 }

我怎样才能得到" a1"," b2"和" c3"? (V是数字而不是字符串)

4 个答案:

答案 0 :(得分:3)

那是诀窍吗? :

set U to {"a", "b", "c"}
set V to {1, 2, 3}
set X to {}
repeat with i from 1 to number of items in U
    set end of X to ((item i of U) & (item i of V)) as text
end repeat

答案 1 :(得分:2)

几乎与Zero相同的代码,但如果一个比另一个短,它会检查列表U和V的长度。第二个区别是摆脱了括号。当您在AppleScript中连接数据并且连接的第一项是字符串时,所有其他值将自动强制转换为字符串对象。

set U to {"a", "b", "c"}
set V to {1, 2, 3}
set i to 1
set R to {}
repeat until i > (count of U) or i > (count of V)
    set end of R to item i of U & item i of V
    set i to i + 1
end repeat
return R

答案 2 :(得分:0)

此脚本从您的示例开始,循环遍历第一个数组,并使用计数器添加第二个数组的项目。然后它将新字符串转换为列表。

-- your example
set u to {"a", "b", "c"}
set v to {1, 2, 3}
-- prepare variables
set x to "" as text
set counter to 0
-- loop through the two arrays
repeat with c in u as text
    set counter to counter + 1
    set x to x & (c & item counter of v) & ","
end repeat
-- remove last comma
set len to the length of x
set x to characters 1 thru (len - 1) of x as text
-- convert string x to list x
set AppleScript's text item delimiters to ","
set x to every text item of x
-- display result
return x

此脚本生成{"a1","b2","c3"}

答案 3 :(得分:-1)

这是另一种方法......

set U to {"a", "b", "c"}
set V to {1, 2, 3}
set text item delimiters to ","
set {U, V} to {U as text, V as text}
set text item delimiters to {return & space, return}
set X to text items 1 thru -2 of (do shell script "echo {" & U & "}{" & V & "}'\\n'")
set text item delimiters to ""