初步想法:
>>> 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]