美文网首页
python列表--查找集合中重复元素的个数

python列表--查找集合中重复元素的个数

作者: 逍遥_yjz | 来源:发表于2018-10-16 17:03 被阅读0次

    方法一:

    >>> mylist = [1,2,2,2,2,3,3,3,4,4,4,4]
    
    >>> myset = set(mylist)
    
    >>> for item in myset:
    
             print("the %d has found %d" %(item,mylist.count(item)))
    

    the 1 has found 1

    the 2 has found 4

    the 3 has found 3

    the 4 has found 4

    方法二:

    >>> from collections import Counter
    
    >>> Counter([1,2,2,2,2,3,3,3,4,4,4,4])
    
    Counter({2: 4, 4: 4, 3: 3, 1: 1})
    
    

    方法三:

    >>> List=[1,2,2,2,2,3,3,3,4,4,4,4]
    
    >>> a = {}
    
    >>> for i in List:
    
             if List.count(i)>1:
    
                       a[i] = List.count(i)
    
            
    
    >>> print (a)
    
    # most_common(n) 按照counter的计数,按照降序,返回前n项组成的list; n忽略时返回全部
    >>> Counter('abracadabra').most_common(3)
    [('a', 5), ('r', 2), ('b', 2)]
    

    参考资料:
    # python列表--查找集合中重复元素的个数

    https://www.cnblogs.com/nisen/p/6052895.html

    相关文章

      网友评论

          本文标题:python列表--查找集合中重复元素的个数

          本文链接:https://www.haomeiwen.com/subject/eewhzftx.html