-1

I need a lot of nested loops and want to use itertool's product. The following does what I want:

for v9,v8,v7,v6,v5,v4,v3,v2,v1 in itertools.product([0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1],[0,1]):
    #do something with v1,v2,v3,v4,v5,v6,v7,v8,v9

However, it is far from elegant. Is there a way to write it in a neater way? It would be nice to "outsource" the arguments of the itertools.product in some way such that one can adapt it better. I mean something like

lim = 10
var = [f"v{i}" for i in range(1,lim)]
kar = [[0,1] for _ in range(1,lim)]
for var in itertools.product(kar): 
    #do something

I'm fully aware that this cannot work in various dimensions, I just wrote it to make clear what I have in mind.

Juri V
  • 1
  • 3
  • `for v in itertools.product(...): for x in v: ...`…?! – deceze Mar 14 '23 at 08:40
  • 1
    What do you _want_ to do with `v*`? – deceze Mar 14 '23 at 08:41
  • 1
    If your use case is just a list of one and zeros, you could do `for var in range(1 << 9)` and play with each bit. – Jorge Luis Mar 14 '23 at 08:48
  • Did you have a quick look at [the docs](https://docs.python.org/3.7/library/itertools.html#itertools.product)? There is the `repeat` argument so at least you could simplify to `for ... in product([0, 1], repeat=n)` – Tomerikoo Mar 14 '23 at 08:53
  • @Tomerikoo thanks a lot! This solves the issue. Tbh I'm wondering why I struggled so much with it - the solution is very easy... – Juri V Mar 14 '23 at 08:56
  • ***Always*** check the docs... It has a lot of useful information. Also, someone bothered to write it - it would be a shame not to use it :) – Tomerikoo Mar 14 '23 at 08:57

1 Answers1

-1

You can acces your variables using indexes:

lim = 10
var = [f"v{i}" for i in range(1,lim)]
kar = [[0,1] for _ in range(1,lim)]

for var in itertools.product(*kar): 

    print(f"v1 = {var[-1]}")
    print(f"v2 = {var[-2]}")
    print(f"v3 = {var[-3]}")
    print(f"v4 = {var[-4]}")
    print(f"v5 = {var[-5]}")
    print(f"v6 = {var[-6]}")
    print(f"v7 = {var[-7]}")
    print(f"v8 = {var[-8]}")
    print(f"v9 = {var[-9]}")
    

This solution is robust with dimensions.

Vincent Bénet
  • 1,212
  • 6
  • 20