15

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

1
  • 1
    if i == "hit": is wrong, i is a list Commented Feb 12, 2014 at 9:14

3 Answers 3

23

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
Sign up to request clarification or add additional context in comments.

2 Comments

can 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?
@user2212774, It's list comprehension. 'list.count' does not search nested list. It only match its items.
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))

Comments

0
Transaction=[['Mango','Onion','Jar','Key-chain','Eggs','Chocolates'],
['Nuts','Onion','Jar','Key-chain','Eggs','Chocolates'],
['Mango','Apple','Key-chain','Eggs'],
['Mango','Toothbrush','corn','Key-chain','Chocolates'],
['corn','Onion','Key-chain','Knife','Chocolates']
]
count1=[['Mango',0],['Onion',0],['Jar',0],['Key-chain',0],['Eggs',0],
['Chocolates',0],['Nuts',0],['Apple',0],['Toothbrush',0],['corn',0],['Knife',0]]
for j in range(0,10):
 x=0
for i in range(0,5):
 x=x+Transaction[i].count(count1[j][0]);
count1[j][1]=x
print count1

1 Comment

you should explain the code, add some text along with it, not just post it like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.