Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting 2d lists in python

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

like image 499
user2212774 Avatar asked Feb 12 '14 09:02

user2212774


1 Answers

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
like image 80
falsetru Avatar answered Oct 28 '22 02:10

falsetru