numpy - How do I write many nested for-loops in a few lines of Python code? -
what have: have list list123=[-13,3,12,1]
, 2-by-4-matrix matrix123=numpy.zeros((2,4), dtype=decimal)
.
what want: want change entries of matrix entry of list , print terminal. there 4^(2*4)=65536 possible combinations. want print every combination.
how now: here current code:
list123=[-13,3,12,1] matrix123=numpy.zeros((2,4), dtype=decimal) k=0 k in list123: matrix123[0,0]=k k in list123: matrix123[0,1]=k k in list123: matrix123[0,2]=k k in list123: matrix123[0,3]=k k in list123: matrix123[1,0]=k k in list123: matrix123[1,1]=k k in list123: matrix123[1,2]=k k in list123: matrix123[1,3]=k print matrix123 print " "
my question: what more compact way write in few lines of code? need same 23-by-27 matrix. mean have write code 23*27=621 for-loops manually, if don't find more compact way.
you can use itertools.product
:
import itertools list123 = [-13, 3, 12, 1] matrix in itertools.product(list123, repeat=8): print matrix
it output possible solution of length 8 -13, 3, 12 , 1
. matrix
tuple 8 numbers, being possible solutions.
if need output result in real numpy.matrix
form, can create them on fly (even though take more time).
import numpy np prod in itertools.product(list123, repeat=8): print np.matrix([prod[:4], prod[4:]])
or using reshape
improve readability (thanks @menglongli)
for prod in itertools.product(list123, repeat=8): print np.reshape(prod, (2, 4))
it gave 65536 results expected.
Comments
Post a Comment