Counting 2d lists in python
11,722
Solution 1
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
Solution 2
If I had code that used 2D lists quite a bit, I would make a generator that returns each element in a 2D list:
def all_elements_2d(l):
for sublist in l:
for element in sublist:
yield element
And then you can do other things with it, like count all the 'hit' strings:
hits = sum(element == 'hit' for element in all_elements_2d(grid))
Author by
user2212774
Updated on July 23, 2022Comments
-
user2212774 almost 2 years
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
-
user2212774 about 10 yearscan you explain why [row.count('hit') for row in grid] is within brackets? also, how is this counting within the nested lists? i.e., if I wrote print grid.count("hit"), why doesn't that count through all the lists? I know I can write something like grid[1].count which will count within the second list, but how is your code accessing the contents of all the nested lists?
-
falsetru about 10 years@user2212774, It's list comprehension. 'list.count' does not search nested list. It only match its items.
-
Kristijan Iliev almost 9 yearsyou should explain the code, add some text along with it, not just post it like that.