迭代许多不同变量的更好方法

时间:2017-07-17 16:37:08

标签: python

我想迭代许多不同的变量。目前,我的代码如下所示:

    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 个答案:

答案 0 :(得分: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')]