2015-12-22 55 views
3

Applescript,我試圖讓列表出現在一個對話框中只有3個項目的總數量。例如,我有5個可能項目的列表,我想讓對話框顯示3個隨機項目,但沒有重複項目。我不知道我是否在正確的軌道上,但我堅持。Applescript,我試圖使一個對話框中出現一個對話框,我只有總數量的3我有

set myList to {"Apples", "Bananas", "Oranges", "Grapes", "Turkey"} 

set r to some item of myList 

set newList to (myList without r) 

set t to some item of newList 

set newerList to (newList without t) 

newList 
+1

一種更好的方式來解釋它是這樣的:設置MYLIST爲{「鮑勃」,「布萊恩」,「馬」,「約書亞」,「莎拉」,「喬治」}如列表 重複 \t顯示對話框的一些項目mylist end repeat我希望能夠做一個以上的隨機名稱,但不能重複。所以,我不想得到鮑勃鮑勃或薩拉薩拉喬治。我想得到鮑勃莎拉,或喬治布萊恩馬克,或我想要的許多,只是不重複。 – Jk42

+0

如果答案解決了您的問題,請點擊旁邊的大號複選標記(✓)接受答案。 如果您發現其他答案有幫助,請投票給他們。接受和投票答案不僅有助於回答者,也有助於未來的讀者。請參閱[相關幫助中心文章](http://stackoverflow.com/help/someone-answers)。如果您的問題尚未得到充分解答,請提供反饋。 – mklement0

回答

0

該解決方案使用重複循環,該循環直到達到最大數量的項目時才執行。

property maxItemsInNewList : 3 

set newList to {} 
set myList to {"Apples", "Bananas", "Oranges", "Grapes", "Turkey"} 
repeat while (count newList) < maxItemsInNewList 
    set r to some item of myList 
    if newList does not contain r then set end of newList to r 
end repeat 
newList 
+0

由於碰撞,此腳本可以永久運行。特別是當使用更大的列表,其結果是'count newList = maxItemsInNewList'。 –

+0

正如mklement0指出的那樣,當newList的大小接近myList的大小時,更多的是碰撞上升的次數問題 –

0

要與使用do shell script解決方案補充dj bazzie wazzie's helpful pure AppleScript answer調用perl,這使得洗牌名單很容易:

# Input list. 
set myList to {"Apples", "Bananas", "Oranges", "Grapes", "Turkey"} 

# Convert the list to a string with each item on its own line. 
set AppleScript's text item delimiters to "\n" # ' perhaps restore original val. later 
set myTextList to myList as text 

# Set the number of random items to extract, without replacement. 
set sampleSize to 3 

# Call the shell to let Perl shuffle the lines, then 
# convert the lines back into a list and extract the first 3 items. 
set randomSample to paragraphs 1 thru sampleSize of ¬ 
    (do shell script "perl -MList::Util=shuffle -e 'print shuffle <>' <<<" & ¬ 
    quoted form of myTextList) 
1

一種不同的方法比vadian的。 vadian腳本的問題在於,如果劇本持續選取之前拍攝的項目,理論上腳本可以永久運行。因此,最好有一個沒有碰撞的解決方案。這需要花費更多的精力,因爲在每次拾取物品之後,必須從列表中刪除該值。由於在AppleScript中沒有簡單的命令來執行此操作,因此腳本必須「手動」執行此操作。

最簡單的方法是創建一個包含輸入列表索引的並行列表,在每次迭代中選擇一個隨機索引,並將其設置爲非整數值。這樣我們確保物品只被挑選一次。

set myList to {"Apples", "Bananas", "Oranges", "Grapes", "Turkey"} 
set idxList to {} 
-- first create a list with indexes 
repeat with x from 1 to count myList 
    set end of idxList to x 
end repeat 

set newList to {} 
repeat 3 times 
    -- pick a random index 
    set theIndex to some integer of idxList 
    -- add item to newlist based on picked index 
    set end of newList to item theIndex of myList 
    -- set the picked index to missing value so it will not be picked again 
    set item theIndex of idxList to missing value 
end repeat 
newList 
相關問題