【问题标题】:python itertools combination scalabilitypython itertools 组合扩展性
【发布时间】:2012-08-06 00:13:58
【问题描述】:

我设法修改了我在 Internet 上找到的示例代码,以从文件夹中找到一组文件的所有可能组合,每组 2 个文件。

如果我有一个包含以下文件的文件夹 testfile1、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

整个想法并不是在标准输出上实际显示输出,而是将它们用作子进程调用中的参数。

有什么建议吗?

【问题讨论】:

    标签: python combinations itertools


    【解决方案1】:
    x=3
    
    for combination in itertools.combinations(files, x):
      counter = counter + 1
      output = " and ".join(combination)
      print output, counter
    

    命令行参数可以通过sys.argv获取

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多