Two-dimensional arrays include:I'd like to count how many numbers are in each array. What should I do?
If anyone knows, please let me know.
Two-dimensional array of interest:
two_array_list=[0,0,0, 'None', [1,1, 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None']
desired output:
[3,2,0,0]
# or
3
2
0
0
I think you can use .count.
For example, how about the following?
two_array_list=[0,0,0, 'None', [1,1, 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None']
for list in two_array_list:
n = list.count ("None")
print(len(list)-n)
Instead of counting
how many numbers?
Counting "How many None" and subtracting that number from each list.
Take sum()
using int(True)==1
, int(False)==0
.
from numbers import Number
two_array_list = [
[0,0,0, 'None',
[1, 1, 'None', 'None',
['None', 'None', 'None', 'None', 'None',
['None', 'None', 'None', 'None']
]
counts = [sum(isinstance(v, Number) for vina) for a two_array_list ]
print(counts)
#=>
[3, 2, 0, 0]
Me:
Are the numbers and 'None' only included in the list?
Dear hideto.T:
Numeric and string only.
Then you don't need to use isinstance()
and you can do the following:
counts = [sum(v!='None' for vina) for a two_array_list ]
You can do it by applying this article and list inclusion.
count how many of an object type there are in a list Python
a=[1,1.23, 'abc', 'ABC', 6.45, 2, 3, 4, 4.98]
sum(isinstance(i,int)for i in a)
I think it will look like this.
two_array_list=[0,0,0, 'None', [1,1, 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None']
result = [sum(isinstance(i, int) for i in a) for a two_array_list ]
print(result)
In addition, if int
is included as well as float
, this article (the first answer, not the resolution mark in ) should be applied.
How to accept the input of both int and float types?
if isinstance(num, (int, float)):
#dostuff
It will look like this.
two_array_list=[0,0,0, 'None', [1,2.5, 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None']
result = [sum(isinstance(i, (int, float)) for i in a) for a two_array_list ]
print(result)
© 2025 OneMinuteCode. All rights reserved.