You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AppleScript技术问题:如何对带数字前缀的语句/段落列表排序?

如何按数字顺序排序AppleScript中的问题列表?

要实现按每个问题开头的数字序号排序,你需要自定义排序规则——提取每个字符串的前置数字作为排序依据,避免AppleScript默认字符串排序的逻辑误差(比如默认排序会把"10."排在"2."前面)。

完整实现代码

set questionList to {
    "10. If you could have any superpower, what would it be and why?",
    "1. What’s the most adventurous thing you’ve ever done?",
    "3. If you could travel back in time, which historical event would you want to witness?",
    "4. What’s your favorite book or movie, and why does it resonate with you?",
    "7. If you were stranded on a deserted island, what three items would you want to have with you?",
    "2. What’s a skill or hobby you’ve always wanted to learn but haven’t yet?",
    "8. If you could meet any famous person (dead or alive), who would it be and what would you ask them?",
    "5. What’s the best piece of advice you’ve ever received?",
    "9. If you could instantly master any musical instrument, which one would you choose?",
    "6. What’s a place you’ve never been to but would love to visit someday?"
}

-- 定义提取前置数字的辅助函数
on extractNumber(questionStr)
    set dotPos to offset of "." in questionStr
    return (text 1 thru (dotPos - 1) of questionStr) as integer
end extractNumber

-- 按提取的数字排序列表
set sortedQuestionList to sort questionList by (my extractNumber(item))

-- 验证结果(可选)
log sortedQuestionList

代码说明

  1. 辅助函数extractNumber:遍历每个问题字符串,找到.的位置,截取前面的数字部分并转为整数,作为排序的核心依据。
  2. 自定义排序:使用AppleScript的sort命令,通过my extractNumber(item)指定排序键,让列表按数字序号从小到大排列。
  3. 输出结果:运行后sortedQuestionList会得到严格按1到10顺序排列的问题列表。

内容的提问来源于stack exchange,提问作者Boin Pendlum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 07:39:59