2012-08-05 80 views
1

我設法修改我在互聯網上找到的示例代碼,以從一個文件夾內找到一組文件中的所有可能組合。python itertools組合的可擴展性

如果我有一個文件夾測試其中包含以下文件:文件1,文件2,文件3,文件4和運行下面的代碼:

import os, itertools, glob 
folder = "test" 

files = glob.glob(folder + "/*") 
counter = 0 
for file1, file2 in itertools.combinations(files, 2): 
    counter = counter + 1 
    output = file1 + " and " + file2 
    print output, counter 

我的輸出是這樣的:

test/file1 and test/file2 1 
test/file1 and test/file3 2 
test/file1 and test/file4 3 
test/file2 and test/file3 4 
test/file2 and test/file4 5 
test/file3 and test/file4 6 

這是完美的列出2個文件的所有可能的組,而不重複。現在,因爲我有我的for循環硬編碼,我遇到的問題擴大到「x」文件組,並保持代碼簡單。 IE瀏覽器,我想「X」被用戶選擇,如果他選擇3,腳本將顯示的輸出:

test/file1 and test/file2 and test/file3 1 
test/file1 and test/file2 and test/file4 2 
test/file1 and test/file3 and test/file4 3 
test/file2 and test/file3 and test/file4 4 

整個想法是不實際顯示在標準輸出上輸出,但將它們用作子進程調用中的參數。

有什麼建議嗎?

回答

4
x=3 

for combination in itertools.combinations(files, x): 
    counter = counter + 1 
    output = " and ".join(combination) 
    print output, counter 

命令行參數可與sys.argv

+0

那是快中獲取,非常完美,非常感謝! – Nick 2012-08-05 16:23:12