I have an array: x = [ [1, 2], 1, 1, [2, 1, [1, 2]] ]
in which I want to count every occurrence of the number 1, and store that number in the variable one_counter. x.count(1) returns only 2 occurrences of 1, which is insufficient.
My code below serves my purpose and stores 5 in one_counter, however it looks messy and feels unpythonic to me.
Any suggestions how I can improve its pythonicity and expand it into more-dimensional lists?
Thanks!
x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
one_counter = 0
for i in x:
if type(i) == list:
for j in i:
if type(j) == list:
for k in j:
if k == 1:
one_counter += 1
else:
if j == 1:
one_counter += 1
else:
if i == 1:
one_counter += 1