我创建了一个3D列表。现在,我想计算该3d列表中数字的出现次数。
print("Enter matrix entries column wise one matrix after another:\n")
lists=[[[int(input()) for _ in range(o)] for _ in range(a)] for _ in range(c)]
print(lists)
我已经完成了这段代码来创建3d列表。在这里,o = 4(行数),a = 3(列数),c = 2(矩阵数)(以前由用户提供),矩阵仅包含1,2,3,4和5。< / p>
Enter matrix entries column wise one matrix after another:
1
1
2
3
4
5
1
2
3
4
5
1
2
1
1
1
1
1
1
2
2
3
3
4
4
[[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2]], [[1, 1, 1, 1], [1, 1, 2, 2], [3, 3, 4, 4]]]
,我得到了这个输出,这是理想的情况。我们可以将生成的3d列表视为
matrix1= 1 5 4
2 1 5
3 2 1
4 3 2
matrix2= 1 2 3
1 2 3
1 2 3
1 2 3
现在我想要一个3d列表,上面写着“ counts”,看起来像这样:
[[[[1,1,1],[1,1,1],[1,1,0],[1,0,1],[0,1,1]],[[4, 0,0],[0,4,0],[0,0,4],[0,0,0],[0,0,0]]] p
Here counts[0][0][0](i.e. first 1) describes how many 1's are there in first column first matrix.
counts[0][0][1](i.e. second 1) describes how many 1's are there in second column first matrix.
counts[0][0][2](i.e. third 1) describes how many 1's are there in third column first matrix.
counts[0][1][0](i.e. forth 1) describes how many 2's are there in first column first matrix.
counts[0][1][1](i.e. fifth 1) describes how many 2's are there in second column first matrix.
counts[0][1][2](i.e. sixth 1) describes how many 2's are there in third column first matrix.
counts[0][2][0](i.e. seventh 1) describes how many 3's are there in first column first matrix.
counts[0][2][1](i.e. eighth 1) describes how many 3's are there in second column first matrix.
counts[0][2][2](i.e. ninth 0) describes how many 3's are there in third column first matrix.
counts[0][3][0](i.e. tenth 1) describes how many 4's are there in first column first matrix.
counts[0][3][1](i.e. eleventh 0) describes how many 4's are there in second column first matrix.
counts[0][3][2](i.e. 12th 1) describes how many 4's are there in third column first matrix.
counts[0][4][0](i.e. 13th 0) describes how many 5's are there in first column first matrix.
counts[0][4][1](i.e. 14th 1) describes how many 5's are there in second column first matrix.
counts[0][4][2](i.e. 15th 1) describes how many 5's are there in third column first matrix.
以相同的方式[[4,0,0],[0,4,0],[0,0,4],[0,0,0],[0,0,0]]这部分还计算第二矩阵。 请从“列表”列表和“ a”,“ o”,“ c”变量中计算“计数”列表。
答案 0 :(得分:0)
我不确定您要寻找的确切输出是什么,但是可以使用for循环来实现:
lists=[[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2]], [[1, 1, 1, 1], [1, 1, 2, 2], [3, 3, 4, 4]]]
for m_num, matrix in enumerate(lists):
for ind, col in enumerate(matrix):
for i in range(1, 6): # because as you said matrix contains only 1, 2, 3, 4 and 5
print('number of {} in column idn: {}, of {} matrix: {}'.format(i, ind+1, m_num+1, col.count(i)))
您还可以跳过枚举,仅在第一列中然后在第二列中打印数字“ 1”,依此类推:
lists=[[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2]], [[1, 1, 1, 1], [1, 1, 2, 2], [3, 3, 4, 4]]]
for matrix in lists:
for col in matrix:
for i in range(1, 6):
print(col.count(i))