Reputation: 319
I want to iterate over many different variables. At the moment, my code looks like this:
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))
Which is clearly inefficient, and takes a lot of manual labour to add another variable. The reason I want to do this is because I want my variables to be distinct, but I want to try all variations of them. At the moment, I am producing every variation of the combination of these variables and then iterating over them.
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
Is there a better way to do solve this kind of problem?
Upvotes: 0
Views: 56
Reputation: 86306
I think you are looking for itertools.product
. The following should work:
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')]
Upvotes: 5