繁体   English   中英

通过索引以升序对Applescript列表进行排序

[英]Sorting an Applescript list in ascending order by indexing

我正在尝试对从一个文件夹创建的文件名列表进行排序。 这是最简单的形式的代码。 如果我执行此操作,则10总是排在1之后,而不是9之后。

set composer_list to {"Filename_1", "Filename_2", "Filename_3", "Filename_4", "Filename_5", "Filename_6", "Filename_7", "Filename_8", "Filename_9", "Filename_10", "Filename_11"}
simple_sort(composer_list)


--======================================= Sorting Handler =====================================
on simple_sort(my_list)
    set the index_list to {}
    set the sorted_list to {}
    repeat (the number of items in my_list) times
        set the low_item to ""
        repeat with i from 1 to (number of items in my_list)
            if i is not in the index_list then
                set this_item to item i of my_list as text
                if the low_item is "" then
                    set the low_item to this_item
                    set the low_item_index to i
                else if this_item comes before the low_item then
                    set the low_item to this_item
                    set the low_item_index to i
                end if
            end if
        end repeat
        set the end of sorted_list to the low_item
        set the end of the index_list to the low_item_index
    end repeat
    return the sorted_list
end simple_sort

结果:

{"Filename_1", "Filename_10", "Filename_11", "Filename_2", "Filename_3", "Filename_4", "Filename_5", "Filename_6", "Filename_7", "Filename_8", "Filename_9"}

采用:

considering numeric strings
    simple_sort(composer_list)
end considering

结果:

{"Filename_1", "Filename_2", ..., "Filename_9", "Filename_10", "Filename_11"}

这是因为

"Filename_11" comes before "Filename_2" -- true

如果您将列表清零,它应该可以工作。

"Filename_11" comes before "Filename_02" -- false

您应该下载Nigel Garvey的“排序剂量”以获得最佳排序例程。

但是,我对此问题有一个变体:

我有一个带连字符的节和小节的列表,使用以连字符分隔的数字(第1节,第1-3节,第1-3-5节,第2-0节)。 使用原始的simple_sort,1-3-5将在1-3之前出现。 但是,使用“考虑数字字符串”而不是将连字符视为减号,并且所有内容都变得混乱。 但是,我添加了另一个子例程来通过在比较之前删除连字符来对所比较的字符串进行预处理:

on removeHyphens(theText)
set AppleScript's text item delimiters to "-"
set theReturn to every text item of theText
set AppleScript's text item delimiters to ""
set theReturn to theReturn as string
return theReturn
end removeHyphens

然后在simple_sort函数中,我将这一行更改为:否则,如果removeHyphens(this_item)在removeHyphens(low_item)之前出现,则

在这种特定情况下,这就像一种魅力。

如何忽略连字符...结束忽略

但是最好的答案是:使用Filename_01(前导0填充)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM