safnasfsa
safnasfsa

Reputation: 117

Creating matrix with for loop in python

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

Upvotes: 0

Views: 605

Answers (3)

RufusVS
RufusVS

Reputation: 4127

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

Upvotes: 2

0stone0
0stone0

Reputation: 43983

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

Upvotes: 0

0x5961736972
0x5961736972

Reputation: 148

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)

Upvotes: -1

Related Questions