I'm looking to count the number of occurrences of an empty array within a 2D array in the most efficient manner. For example :
array = [[a,b],[a,b,c],[a],[],[],[],[]]
The answer I would like to get should be 4
.
How do we get around doing that without using a lengthy for loop process? It shouldn't also use Numpy, just plain simple Python. I tried .count, but I doesn't quite work with empty arrays.
Here is my short solution using the list.count()
method:
array = [[a,b],[a,b,c],[a],[],[],[],[]]
print(array.count([])) # 4
array = [[a,b],[a,b,c],[a],[],[],[],[]]
answer = len([a for a in array if not a])
>>> answer
4
array = [[1,2],[1,2,3],[1],[],[],[],[]]
print(sum(1 for arr in array if not arr)) # 4
I would use the array.count([])
method but just introducing an option that has not been displayed
print(len(list(filter(lambda x: x == [], array))))
# 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.