Count elements in a list python

前端 未结 6 1416
有刺的猬
有刺的猬 2021-01-26 14:14

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,         


        
相关标签:
6条回答
  • 2021-01-26 14:30

    Since you asked for a function:

    def count_O (top_board):
        if True in ["O" in e for e in top_board]:
            print "O found"
    
    0 讨论(0)
  • 2021-01-26 14:34
    cnt = sum([lst.count('O') for lst in top_board])
    # then do something depending on cnt
    
    0 讨论(0)
  • 2021-01-26 14:36

    Try this:

    sum(x.count("O") for x in top_board)
    
    0 讨论(0)
  • 2021-01-26 14:38
    if [j for i in top_board for j in i].count('O'):
        print "O is present in the list"
    
    0 讨论(0)
  • 2021-01-26 14:42
    def count_O(l):
        count = 0
        for sublist in l:
            count += sublist.count("O")
        return count
    
    
    if count_O(top_board) == 0:
        #do something
    
    0 讨论(0)
  • 2021-01-26 14:42

    Update

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

    (hadn't notice the nesting...)

    0 讨论(0)
提交回复
热议问题