Count Elements In A List Python
I need to be able to count how many of the string 'O' is in my list top_board = [ [None, None, None, None, None, None, None, None, None], [None, None, None, None, None, No
Solution 1:
cnt = sum([lst.count('O') for lst in top_board])
# then do something depending on cnt
Solution 2:
Try this:
sum(x.count("O") for x in top_board)
Solution 3:
def count_O(l):
count = 0
for sublist in l:
count += sublist.count("O")
return count
if count_O(top_board) == 0:
#do something
Solution 4:
if [j for i in top_board for j in i].count('O'):
print "O is present in the list"
Solution 5:
Update
sum([sum([1 for x in y if x == "O"]) for y in top_board])
(hadn't notice the nesting...)
Post a Comment for "Count Elements In A List Python"