我需要能够计算我的列表中有多少字符串“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]
]
现在我需要一个函数来检查列表中是否有0“O”,然后是否打印出来
答案 0 :(得分:5)
cnt = sum([lst.count('O') for lst in top_board])
# then do something depending on cnt
答案 1 :(得分:2)
试试这个:
sum(x.count("O") for x in top_board)
答案 2 :(得分:0)
更新
sum([sum([1 for x in y if x == "O"]) for y in top_board])
(没注意到嵌套......)
答案 3 :(得分: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
答案 4 :(得分:0)
if [j for i in top_board for j in i].count('O'):
print "O is present in the list"
答案 5 :(得分:0)
因为你要求一个功能:
def count_O (top_board):
if True in ["O" in e for e in top_board]:
print "O found"