如何在AppleScript中移除列表内的指定项目
有没有办法在AppleScript中移除列表里的指定项目?
具体需求可参考如下示例:set theList to {1, 2, 3, 4, 5} remove item 3 of theList log theList --Should log: (*1, 2, 4, 5*)
实现方法
AppleScript本身没有内置的remove语法,你可以通过以下两种常用方式实现需求:
1. 按索引移除指定位置的项目
适配你需求的极简写法:
set theList to {1, 2, 3, 4, 5} -- 移除第3项:拼接前2项和第4项及之后的内容 set theList to items 1 thru 2 of theList & items 4 thru end of theList log theList -- 输出:(*1, 2, 4, 5*)
如果需要频繁调用,可封装为通用函数:
on removeItemAtIndex(targetList, index) set listLength to count of targetList -- 索引不合法直接返回原列表 if index < 1 or index > listLength then return targetList -- 移除第一项 if index = 1 then return items 2 thru end of targetList -- 移除最后一项 if index = listLength then return items 1 thru -2 of targetList -- 移除中间项 return (items 1 thru (index - 1) of targetList) & (items (index + 1) thru end of targetList) end removeItemAtIndex -- 调用示例 set theList to {1, 2, 3, 4, 5} set theList to removeItemAtIndex(theList, 3) log theList
注意:AppleScript的列表索引从1开始计数,不要使用其他语言常用的0作为起始索引。
2. 按值移除所有匹配的项目
如果需要删除列表中所有等于指定值的项目,可使用遍历过滤的方式:
on removeItemByValue(targetList, value) set newList to {} repeat with itemContent in targetList if contents of itemContent is not value then set end of newList to contents of itemContent end if end repeat return newList end removeItemByValue -- 调用示例 set theList to {1, 2, 3, 3, 4, 5} set theList to removeItemByValue(theList, 3) log theList -- 输出:(*1, 2, 4, 5*)
内容的提问来源于stack exchange,提问作者gurkensaas
相关产品推荐
相关产品推荐

