初步想法:

>>> a = [1,2,4,1,2,3,5,2,6,8,7,8,8]
>>> a
[1, 2, 4, 1, 2, 3, 5, 2, 6, 8, 7, 8, 8]
>>> for i in a:
        print(i,a.count(i))

    
1 2
2 3
4 1
1 2
2 3
3 1
5 1
2 3
6 1
8 3
7 1
8 3
8 3

但是,结果出现了重复的值。

有以下三种解决方案:

1.使用集合Set

>>> for i in set(a):
        print(i,a.count(i))

    
1 2
2 3
3 1
4 1
5 1
6 1
7 1
8 3

2.使用字典Dict

>>> d = {}
>>> for i in a:
        if i in d:
        d[i] += 1
        else:
        d[i] = 1

        
>>> print(d)
{1: 2, 2: 3, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 3}

3.使用Counter

>>> from collections import Counter
>>> print(dict(Counter(a)))
{1: 2, 2: 3, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 3}

 

 附:

1.判断列表中是否有重复元素

len(a) == len(set(b))

 2.有的话,有哪些重复元素

>>> a = [1, 2, 4, 1, 2, 3, 5, 2, 6, 8, 7, 8, 8]
>>> d = {}
>>> for i in a:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1

        
>>> d
{1: 2, 2: 3, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 3}
>>> for i in d:
        if d[i] != 1:
            print("元素%d 出现次数%d次" %(i,d[i]))

        
元素1 出现次数2次
元素2 出现次数3次
元素8 出现次数3次

>>> {i:d[i] for i in d if d[i]!=1}
{8: 3, 1: 2, 2: 3}
>>> {key:value for key,value in d.items() if value != 1}
{8: 3, 1: 2, 2: 3}

 3.消除其中的重复元素

>>> a = [1, 2, 4, 1, 2, 3, 5, 2, 6, 8, 7, 8, 8]
>>> b = []
>>> for i in a:
    if i not in b:
        b.append(i)

        
>>> b
[1, 2, 4, 3, 5, 6, 8, 7]

 

 

posted on 2013-04-18 11:18  101010  阅读(11232)  评论(0编辑  收藏  举报