常遇到的問題
- find the duplicate elements in the list
- count the duplicate elements in the list
- remove the duplicate elements in the list
List.count() 用法
計算指定的值在 list 出現幾次
語法:list.count(element)
input:
1 | my_list = [2, 3, 1, 4, 2, 5, 3, 7] |
output:
1 | 2 |
進階
將 list 裡面所有的 element 都記錄下有幾個
input:
1 | dup_list = ["a", "c", "a", "c", "b", "a"] |
output:
1 | {'a': 3, 'c': 2, 'b': 1} |
另一種用法 Counter
需要先 import
語法:
from collections import Counter
Counter(List/String)
counter 出來的型態通常會轉成 Dictionary 會比較方便~
在下面也會示範有轉成 dict 跟沒轉成 dict 的差別
input:
1 | from collections import Counter |
output:
1 | {'a': 3, 'c': 2, 'b': 1} |
Counter 的額外用法
找出出現次數前 n 多
語法: Counter.most_common()
input:
1 | # 接續上一個例子 |
output:
1 | [('a', 4)] |