Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop python?

I need help creating a for loop or suggestions on how to do this better. I have an empty list of 0's based on number of rows and columns. Then another list that contains the data.

I wrote down manually how to change the values to visualize it.

r = 2
c = 2
all_list = [[0 for x in range(c*3)] for y in range(3*r)]
a = [[[' ', 55, ' '], [57, 0, 63], [' ', 43, ' ']], [[' ', 71, ' '], [95, 1, 64], [' ', 37, ' ']], [[' ', 80, ' '], [12, 2, 49], [' ', 69, ' ']], [[' ', 63, ' '], [54, 3, 17], [' ', 84, ' ']]]

#Need to convert the list above to this.
#[[' ', 55, ' ', ' ', 71, ' '], [57, 0, 63, 95, 1, 64], [' ', 43, ' ', ' ', 37, ' '], [' ', 80, ' ', ' ', 63, ' '], [12, 2, 49, 54, 3, 17], [' ', 69, ' ', ' ', 84, ' ']]

all_list[0][0] = a[0][0][0]
all_list[0][1] = a[0][0][1]
all_list[0][2] = a[0][0][2]
all_list[0][3] = a[1][0][0]
all_list[0][4] = a[1][0][1]
all_list[0][5] = a[1][0][2]

all_list[1][0] = a[0][1][0]
all_list[1][1] = a[0][1][1]
all_list[1][2] = a[0][1][2]
all_list[1][3] = a[1][1][0]
all_list[1][4] = a[1][1][1]
all_list[1][5] = a[1][1][2]

all_list[2][0] = a[0][2][0]
all_list[2][1] = a[0][2][1]
all_list[2][2] = a[0][2][2]
all_list[2][3] = a[1][2][0]
all_list[2][4] = a[1][2][1]
all_list[2][5] = a[1][2][2]

all_list[3][0] = a[2][0][0]
all_list[3][1] = a[2][0][1]
all_list[3][2] = a[2][0][2]
all_list[3][3] = a[3][0][0]
all_list[3][4] = a[3][0][1]
all_list[3][5] = a[3][0][2]

all_list[4][0] = a[2][1][0]
all_list[4][1] = a[2][1][1]
all_list[4][2] = a[2][1][2]
all_list[4][3] = a[3][1][0]
all_list[4][4] = a[3][1][1]
all_list[4][5] = a[3][1][2]

all_list[5][0] = a[2][2][0]
all_list[5][1] = a[2][2][1]
all_list[5][2] = a[2][2][2]
all_list[5][3] = a[3][2][0]
all_list[5][4] = a[3][2][1]
all_list[5][5] = a[3][2][2]
print(all_list)

Here is what I have so far:

  for i in range(len(all_list)):
        for j in range(r*c):
            for k in range(r):
                for t in range(3):
                    all_list[i][j] = a[][k][t] #This is not correct
like image 935
Abhi Avatar asked Jul 22 '26 14:07

Abhi


2 Answers

This works:

firstHalf = [thing[0]+thing[1] for thing in zip(*a)]
secondHalf = [thing[2]+thing[3] for thing in zip(*a)]
reshaped = firstHalf + secondHalf

Output

[[' ', 55, ' ', ' ', 71, ' '],
 [57, 0, 63, 95, 1, 64],
 [' ', 43, ' ', ' ', 37, ' '],
 [' ', 80, ' ', ' ', 63, ' '],
 [12, 2, 49, 54, 3, 17],
 [' ', 69, ' ', ' ', 84, ' ']]
like image 178
Garrett R Avatar answered Jul 24 '26 05:07

Garrett R


From an answer I wrote a long time ago:

def nested_loop(n, l):
    for c in range(l ** n):
        yield tuple(c // l**x % l for x in reversed(range(n)))

Use it like this, for your case:

for (i, j) , (l, k, m) in zip(nested_loop(2, 6), nested_loop(3, 3)):
    all_list[i][j] = a[k][l][m]

edit: I just noticed k is not quite right, trying to fix it.

like image 38
L3viathan Avatar answered Jul 24 '26 05:07

L3viathan