在python中计算2d列表

时间:2014-02-12 09:11:40

标签: python list loops multidimensional-array

如何计算此二维列表中“点击”的项目数?

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

我知道代码是错误的,但它会让我知道我想做什么,我希望?

感谢

3 个答案:

答案 0 :(得分:11)

使用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]

sum

>>> sum(row.count('hit') for row in grid)
8

答案 1 :(得分:0)

如果我的代码使用了相当多的2D列表,我会创建一个返回2D列表中每个元素的生成器:

def all_elements_2d(l):
    for sublist in l:
        for element in sublist:
            yield element

然后你可以用它做其他事情,比如计算所有'命中'字符串:

hits = sum(element == 'hit' for element in all_elements_2d(grid))

答案 2 :(得分: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