计数列表python中的元素 [英] Count elements in a list python

查看:72
本文介绍了计数列表python中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够计算列表中有多少个字符串"O"

I need to be able to count how many of the string "O" is in my list

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"之类的元素后,它将看起来像这样

after I add elements like "O" and "X" it will look like this

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,然后打印出一些内容

now I need a function that checks if there is 0 of the "O" in my list and if there is then print something

推荐答案

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


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

这篇关于计数列表python中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆