Count elements in a list python

前端 未结 6 2087
暖寄归人
暖寄归人 2021-01-26 14:22

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:27

    Try this:

    sum(x.count("O") for x in top_board)
    
    0 讨论(0)
  • 2021-01-26 14:27
    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:29
    cnt = sum([lst.count('O') for lst in top_board])
    # then do something depending on cnt
    
    0 讨论(0)
  • 2021-01-26 14:32
    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:49

    Update

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

    (hadn't notice the nesting...)

    0 讨论(0)
  • 2021-01-26 14:50

    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)
提交回复
热议问题