1

インターネットで見つけたサンプル コードを修正して、1 つのフォルダー内から 2 つのペアのファイル グループのすべての可能な組み合わせを見つけることができました。

次のファイルを含むフォルダーtestがある場合: file1、file2、file3、file4で、次のコードを実行します。

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

1 に答える 1

4
x=3

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

コマンドライン引数は次のコマンドで取得できますsys.argv

于 2012-08-05T16:13:58.923 に答える