Fastest way to count number of occurrences in a Python list

前端 未结 5 1984
悲&欢浪女
悲&欢浪女 2020-11-30 03:29

I have a Python list and I want to know what\'s the quickest way to count the number of occurrences of the item, \'1\' in this list. In my actual case, the item

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 04:11

    You can convert list in string with elements seperated by space and split it based on number/char to be searched..

    Will be clean and fast for large list..

    >>>L = [2,1,1,2,1,3]
    >>>strL = " ".join(str(x) for x in L)
    >>>strL
    2 1 1 2 1 3
    >>>count=len(strL.split(" 1"))-1
    >>>count
    3
    

提交回复
热议问题