How can I count the number of items that are 'hit' in this 2d list??
grid = [['hit','miss','miss','hit','miss'],
['miss','miss','hit','hit','miss'],
['miss','miss','miss','hit','hit'],
['miss','miss','miss','hit','miss'],
['hit','miss','miss','miss','miss']]
battleships = 0
for i in grid:
if i == "hit":
battleships = battleships + 1
print battleships
I know that code is wrong, but it gives an idea of what I want to do I hope??
thanks
Use list.count
:
>>> ['hit','miss','miss','hit','miss'].count('hit')
2
>>> grid = [['hit','miss','miss','hit','miss'],
... ['miss','miss','hit','hit','miss'],
... ['miss','miss','miss','hit','hit'],
... ['miss','miss','miss','hit','miss'],
... ['hit','miss','miss','miss','miss']]
>>> [row.count('hit') for row in grid]
[2, 2, 2, 1, 1]
And sum
:
>>> sum(row.count('hit') for row in grid)
8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With