对于循环python?
作者:互联网
我需要创建for循环的帮助或有关如何更好地做到这一点的建议.
我有一个基于行和列数的0的空列表.然后是另一个包含数据的列表.
我手动写下了如何更改值以使其可视化.
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)
这是我到目前为止的内容:
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
解决方法:
这有效:
firstHalf = [thing[0]+thing[1] for thing in zip(*a)]
secondHalf = [thing[2]+thing[3] for thing in zip(*a)]
reshaped = firstHalf + secondHalf
输出量
[[' ', 55, ' ', ' ', 71, ' '],
[57, 0, 63, 95, 1, 64],
[' ', 43, ' ', ' ', 37, ' '],
[' ', 80, ' ', ' ', 63, ' '],
[12, 2, 49, 54, 3, 17],
[' ', 69, ' ', ' ', 84, ' ']]
标签:loops,for-loop,python,nested-loops 来源: https://codeday.me/bug/20191027/1943458.html