2017-07-17 42 views
0

我想遍历许多不同的变量。此刻,我的代码看起来是这样的:迭代许多不同变量的更好方法

for d in dissim_amt_a: 
    for b in breakoff_a: 
     for s in score_limit_a: 
      for a in amount_to_start_a: 
       for c in cluster_multiplier_a: 
        for k in kappa_a: 
         for ct in classification_task_a: 
          for ub in use_breakoff_dissim_a: 
           for ga in get_all_a: 
            for hnk in half_ndcg_half_kappa_a: 
             for l in limit_entities_a: 
              for bc in bag_of_clusters_a: 
               for aa in add_all_terms_a: 
                for bb in only_most_similar_a: 
                 for cc in dont_cluster_a: 
                  for dd in top_dt_clusters_a: 
                   for ee in by_class_finetune_a: 
                    variables_to_execute.append((d, b, s, a, c, k, ct, ub, ga, 
                          hnk, l, bc, aa, bb, cc, dd, ee)) 

这显然是低效的,并且需要大量的手工劳动到再添变数。我想这样做的原因是因为我希望我的变量不同,但我想尝试所有变体。目前,我正在生成这些变量组合的每个变体,然后对它们进行迭代。

for vt in variables_to_execute: 
    file_name = average_csv_fn 
    dissim_amt = vt[0] 
    breakoff = vt[1] 
    score_limit = vt[2] 
    amount_to_start = vt[3] 
    cluster_multiplier = vt[4] 
    score_type = vt[5] 
    classification_task = vt[6] 
    use_breakoff_dissim = vt[7] 
    get_all = vt[8] 
    half_ndcg_half_kappa = vt[9] 
    limit_entities = vt[10] 
    bag_of_clusters = vt[11] 
    add_all_terms = vt[12] 
    only_most_similar = vt[13] 
    dont_cluster = vt[14] 
    class_task_index = 0 

有没有更好的方法来解决这类问题?

+1

使用'itertools' –

+0

是否有itertools是特别相关的某些特定部分? – eygrr

+1

我不清楚你正在尝试做什么,但'itertools'提供了简单的方法来迭代排列,组合和产品。这些嵌套循环看起来像迭代产品的一种方式,所以请查看'itertools.product()' –

回答

5

我认为您在寻找itertools.product。下面应该工作:

In [1]: from itertools import product 

In [2]: A = ["a1", "a2", "a3"] 

In [3]: B = ["b1", "b2", "b3"] 

In [4]: C = ["c1", "c2", "c3"] 

In [5]: list(product(A,B,C)) 
Out[5]: 
[('a1', 'b1', 'c1'), 
('a1', 'b1', 'c2'), 
('a1', 'b1', 'c3'), 
('a1', 'b2', 'c1'), 
('a1', 'b2', 'c2'), 
('a1', 'b2', 'c3'), 
('a1', 'b3', 'c1'), 
... 
('a3', 'b1', 'c3'), 
('a3', 'b2', 'c1'), 
('a3', 'b2', 'c2'), 
('a3', 'b2', 'c3'), 
('a3', 'b3', 'c1'), 
('a3', 'b3', 'c2'), 
('a3', 'b3', 'c3')] 
+0

这是正确的。谢谢! – eygrr