1
Hello, I’m a beginner in python and I’m doing an exercise that consists in reading all the numbers of a matrix and adding in another matrix the numbers existing in the previous one and how often they appear. Consequently, the matrix 2 will have two lines, one containing the numbers, and the second how many times they appear. For example, if there is a number 10 and it appears 3 times, the second matrix will have in the first row the number 10, and in the second the number 3, the two in the same column.
NOTE: Consider the first matrix as any already declared.
...
matriz2=[]
linha1 = []
linha2 = []
qntde=0
linha1.append(0)
for l in range(numerodelinhas):
for c in range(numerodecolunas):
qntde = 0
if(linha1.count(matriz[l][c])==0):
if(l==0 and c == 0):
linha1[0]=matriz[0][0]
if(l != 0 or c != 0):
linha1.append(matriz[l][c])
for n in range(numerodelinhas):
qntde = qntde + matriz[n].count(matriz[l][c])
linha2.append(qntde)
matriz2.append(linha1)
matriz2.append(linha2)
cm2=0
for n in matriz2[0]:
print (matriz2[0][cm2]," - ",matriz2[1][cm2])
cm2+=1
The code worked, but I don’t like it at all. There would be a way to make it dry?
In this case it makes no difference but usually it is better to use the
chain.from_iterable
:Counter(chain.from_iterable(matriz))
– nosklo
True @nosklo, I used unpacking for practicality, but in a real case it might not be performative. I will edit the answer, thank you.
– fernandosavio