2

我正在尝试对从一个文件夹创建的文件名列表进行排序。这是代码,因为它是最简单的形式。如果我运行这个,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"}
4

4 回答 4

6

利用:

considering numeric strings
    simple_sort(composer_list)
end considering

结果:

{"Filename_1", "Filename_2", ..., "Filename_9", "Filename_10", "Filename_11"}
于 2013-11-07T09:53:54.730 回答
2

但是,我遇到的这个问题的一个变体:

我有一个带有连字符的部分和小节的列表,使用由连字符分隔的数字(section1、section1-3、section1-3-5、section2-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) 之前,则

对于这种特定情况,这就像一种魅力。

于 2015-03-30T20:51:55.770 回答
1

这是因为

"Filename_11" comes before "Filename_2" -- true

如果您对列表进行零填充,它应该可以工作。

"Filename_11" comes before "Filename_02" -- false

您应该下载 Nigel Garvey 的“A Dose of Sorts”以获得最佳的分类程序。

于 2013-11-06T23:15:23.097 回答
0

忽略连字符怎么样...结束忽略

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

于 2019-06-20T23:10:10.333 回答