How to write many nested for-loops in multiple lines of Python code?

What I have: I have a list List123=[-13,3,12,1]and a 2-by-4-matrix Matrix123=numpy.zeros((2,4), dtype=Decimal).

I want: I want to change all entries of the matrix to any entry in the list, and then print it on the terminal. There are 4 ^ (2 * 4) = 65536 possible combinations. I want to print each combination.

How am I doing it now: Here is my current code:

List123=[-13,3,12,1]

Matrix123=numpy.zeros((2,4), dtype=Decimal)

k=0
for k in List123:
    Matrix123[0,0]=k
    for k in List123:
        Matrix123[0,1]=k
        for k in List123:
            Matrix123[0,2]=k
            for k in List123:
                Matrix123[0,3]=k
                for k in List123:
                    Matrix123[1,0]=k
                    for k in List123:
                        Matrix123[1,1]=k
                        for k in List123:
                            Matrix123[1,2]=k
                            for k in List123:
                                Matrix123[1,3]=k
                                print Matrix123
                                print " "

My question is: What is a more compact way to write this in just a few lines of code? I need to do the same for a 23 by 27 matrix. That would mean I have to write the code for 23 * 27 = 621 for-loops manually if I don't find a more compact way.

+4
3

itertools.product:

import itertools

list123 = [-13, 3, 12, 1]

for matrix in itertools.product(list123, repeat=8):
  print matrix

8 -13, 3, 12 and 1. matrix 8 , .

, numpy.matrix, ( ).

import numpy as np

for prod in itertools.product(list123, repeat=8):
  print np.matrix([prod[:4], prod[4:]])

reshape, ( @MenglongLi)

for prod in itertools.product(list123, repeat=8):
  print np.reshape(prod, (2, 4))

65536 , .

0

itertools python:

from itertools import product
import numpy as np

List123 = [-13, 3, 12, 1]

for i in product(List123, repeat=8):
    print(np.array(i).reshape(2, 4))

:

import numpy as np

List123 = [-13, 3, 12, 1]

def dfs(depth=1, result=None):
    if result is None:
        result = []
    if depth == 9:
        print(np.array(result).reshape(2, 4))
        return

    for i in List123:
        dfs(depth + 1, result + [i])

dfs()

65536 .

+3

np.meshgrid:

def my_product(list, shape = (4,2)):
    r = np.product(shape)
    out = np.stack(np.meshgrid(*(List123,) * r))
    out = out.reshape(shape[::-1] + (-1,)).T
    for mat in list(out):
        print(mat)

Of course, if yours shapeis equal (23,27), this will lead to memerror, even if len(list) = 2, since all these permutations will fill all the memory on earth with a ridiculous number of times and they will all print them until the heat of death of the universe.

+3
source

Source: https://habr.com/ru/post/1685537/


All Articles