2014-03-19 77 views
0

我需要能夠計算有多少字符串「O」的是在我的名單計數元素

top_board = [ 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None] 
] 

後,我添加元素,如「O」和「X」,將看這樣

top_board = [ 
    ["O", None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, "O", None, None, None], 
    [None, None, None, None, None, None, None, "O", None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, "O", None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None], 
    [None, None, None, None, None, None, None, None, None] 
] 

現在我需要檢查是否有在我的列表中的「O」 0的功能,如果有,然後打印東西

+0

你能說清楚你想要什麼嗎?請檢查top_board的任何列表中是否沒有「O」?或者每個列表是否沒有「O」?也就是'sum([lst.count('O')for top_board]]'或'[sum(1 for j in i if if ==「O」)for top_board]'? – fredtantini

回答

0
def count_O(l): 
    count = 0 
    for sublist in l: 
     count += sublist.count("O") 
    return count 


if count_O(top_board) == 0: 
    #do something 
2

試試這個:

sum(x.count("O") for x in top_board) 
+0

'top_board.count(「O」)'? – starrify

+0

Ehh這些錯別字 –

+0

此外,sum([x for x in l])運行(不顯着但明顯)快於sum(x for x in l)'。 (至少在我的機器上):P – starrify

0

更新

sum([sum([1 for x in y if x == "O"]) for y in top_board]) 

(沒有注意到嵌套...)

5
cnt = sum([lst.count('O') for lst in top_board]) 
# then do something depending on cnt 
0
if [j for i in top_board for j in i].count('O'): 
    print "O is present in the list" 
0

既然你問了一個功能:

def count_O (top_board): 
    if True in ["O" in e for e in top_board]: 
     print "O found"