Home > database >  Creating matrix with for loop in python
Creating matrix with for loop in python

Time:12-03

I have a list with 4 elements. Each element is a correct score that I am pulling from a form. For example:

scoreFixed_1 = 1
scoreFixed_2 = 2
scoreFixed_3 = 3
scoreFixed_4 = 4

scoreFixed = [scoreFixed_1, scoreFixed_2, scoreFixed_3, scoreFixed_4]

Then, I need to add:

scoreFixed_1 to fixture[0][0]
scoreFixed_2 to fixture[0][1]
scoreFixed_3 to fixture[1][0]
scoreFixed_4 to fixture[1][1]

Hence, I need to create a triple for loop that outputs the following sequence so I can index to achieve the result above:

0 0 0
1 0 1
2 1 0
3 1 1

I have tried to use this to create this matrix, however I am only able to get the first column correct. Can anyone help?

for x in range(1):
    for y in range(1):
        for z in range(4):
            print(z, x, y)

which outputs:

0 0 0
1 0 0
2 0 0
3 0 0

CodePudding user response:

Your logic does not generate the table, you want something like:

rownum = 0
for x in range(2):
    for y in range(2):
        print (rownum, x, y)
        rownum  = 1

(Edit: The question has been changed, to accomplish the new desire, you want something like this:)

scoreIndex = 0
for x in range(2):
    for y in range(2):
        fixture[x][y]  = scoreFixed[scoreIndex]
        scoreIndex  = 1

CodePudding user response:

After your edit, it seems like we can split the 'sequence' into:

  1. First column, regular ascending variable ( n = 1)
  2. Second and third column, binary counter (00, 01, 10, 11)
0 0 0
1 0 1
2 1 0
3 1 1

  ^ ^------- These seem like a binary counter 
                (00, 01, 10, 11)

^------ A regular ascending variable
                ( n  = 1 )

Using that 'logic' we can create a code that looks like

import itertools 

scoreFixed = 0
for i in itertools.product([0,1],repeat=2): 
    print(scoreFixed, ' '.join(map(str,i)))
    scoreFixed  = 1

And wil output:

0 0 0
1 0 1
2 1 0
3 1 1

As you can test in this online demo

CodePudding user response:

for x in range(4):
    z = int(bin(x)[-1])
    y = bin(x)[-2]
    y = int(y) if y.isdigit() else 0
    print(x, y, z)

CodePudding user response:

You need to create a few conditions inside the last for loop.

flag=False
for x in range(1):
    for y in range(1):
        for z in range(4):
            print(z, x, y)
            if x==0 and flag==True:
                x=1
            else:
                flag=True
            if y==0:
                y=1
            else:
                y=0

CodePudding user response:

Try increasing your for loops at the top

for x in range(10):
for y in range(10):
    for z in range(4):
        print(z, x, y)
  • Related